我怎样才能看到一个Perl哈希已经有一个特定的关键?

我有一个Perl脚本来计算文本文件中各种string的出现次数。 我希望能够检查某个string是否还不是散列中的关键字。 有没有更好的方法来完成这一切?

这是我在做什么:

foreach $line (@lines){ if(($line =~ m|my regex|) ) { $string = $1; if ($string is not a key in %strings) # "strings" is an associative array { $strings{$string} = 1; } else { $n = ($strings{$string}); $strings{$string} = $n +1; } } } 

我相信要检查一个密钥是否存在于你刚刚做的哈希中

 if (exists $strings{$string}) { ... } else { ... } 

那么,你的整个代码可以被限制在:

 foreach $line (@lines){ $strings{$1}++ if $line =~ m|my regex|; } 

如果该值不存在,则++运算符将假定它为0(然后递增为1)。 如果它已经在那里 – 它会简单地增加。

我会劝说不要使用if ($hash{$key})因为如果key存在但是它的值不为0或为空,它不会做你所期望的。

我想这个代码应该回答你的问题:

 use strict; use warnings; my @keys = qw/one two three two/; my %hash; for my $key (@keys) { $hash{$key}++; } for my $key (keys %hash) { print "$key: ", $hash{$key}, "\n"; } 

输出:

 three: 1 one: 1 two: 2 

迭代可以简化为:

 $hash{$_}++ for (@keys); 

(参见perlvar中的 $_ )你甚至可以写这样的东西:

 $hash{$_}++ or print "Found new value: $_.\n" for (@keys); 

哪一个报告第一次发现每个关键。

你可以去:

 if(!$strings{$string}) ....