How can I make hash key lookup case-insensitive?

前提是你 提交于 2020-01-13 08:11:46

问题


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?


回答1:


You will have to use a tied hash. For example Hash::Case::Preserve.




回答2:


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.




回答3:


my %hash = (FOO => 1);
my $key = 'fOo'; # or 'foo' for that matter

my %lookup = map {(lc $_, $hash{$_})} keys %hash;
printf "%s\n", ( exists $hash{(lc $key)} ) ? "Yes" : "No";



回答4:


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.



来源:https://stackoverflow.com/questions/310036/how-can-i-make-hash-key-lookup-case-insensitive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!