显然,哈希键以区分大小写的方式进行比较。
$ 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
是否有一种设置可以更改当前脚本的内容?
字符串的哈希值和大小写不同的相同字符串的哈希值是不相等的。因此,除非在创建哈希键之前和使用哈希键之前都调用“uc”,否则无法实现您想要的操作。
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";
grep
能够解决问题,如果您使模式匹配不区分大小写:
perl -e '%hash = ( FOO => 1 );
printf "%s\n", ( scalar(grep (/^foo$/i, keys %hash)) > 0) ? "是" : "否";'
如果您有多个拼写不同的键,则还需要检查匹配是否大于1。