Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make hash key lookup case-insensitive?

Tags:

hash

perl

Evidently hash keys are compared in a case-sensitive manner.

$ perl -e '%hash = ( FOO => 1 ); printf "%s\n", ( exists $hash{foo} ) ? "Yes" : "No";'
No

$ perl -e '%hash = ( FOO => 1 ); printf "%s\n", ( exists $hash{FOO} ) ? "Yes" : "No";'
Yes

Is there a setting to change that for the current script?

like image 679
mseery Avatar asked Nov 21 '08 20:11

mseery


2 Answers

The hash of a string and the same string with the case changed are not equal. So you can't do what you want, short of calling "uc" on every hash key before you create it AND before you use it.

like image 145
Paul Tomblin Avatar answered Sep 17 '22 13:09

Paul Tomblin


grep should do the trick if you make the pattern match case insensitive:

perl -e '%hash = ( FOO => 1 ); printf "%s\n", ( scalar(grep (/^foo$/i, keys %hash)) > 0) ? "Yes" : "No";'

If you have more then one key with various spelling you may need to check if the match is greater than 1 as well.

like image 23
Pascal Cimon Avatar answered Sep 16 '22 13:09

Pascal Cimon