How can I make hash key lookup case-insensitive?

2019-06-16 04:26发布

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?

标签: perl hash
4条回答
\"骚年 ilove
2楼-- · 2019-06-16 04:36

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.

查看更多
\"骚年 ilove
3楼-- · 2019-06-16 04:41
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楼-- · 2019-06-16 04:47

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.

查看更多
男人必须洒脱
5楼-- · 2019-06-16 04:50

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

查看更多
登录 后发表回答