[英]How can I see if a Perl hash already has a certain key?
I have a Perl script that is counting the number of occurrences of various strings in a text file.我有一个 Perl 脚本,用于计算文本文件中各种字符串的出现次数。 I want to be able to check if a certain string is not yet a key in the hash. Is there a better way of doing this altogether?我希望能够检查某个字符串是否还不是 hash 中的键。有没有更好的方法来完成这项工作?
Here is what I am doing:这是我在做什么:
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;
}
}
}
I believe to check if a key exists in a hash you just do我相信要检查 hash 中是否存在密钥,您只需这样做
if (exists $strings{$string}) {
...
} else {
...
}
I would counsel against using if ($hash{$key})
since it will not do what you expect if the key exists but its value is zero or empty.我建议不要使用if ($hash{$key})
,因为如果键存在但其值为零或空,它不会执行您期望的操作。
Well, your whole code can be limited to:那么,您的整个代码可以限制为:
foreach $line (@lines){
$strings{$1}++ if $line =~ m|my regex|;
}
If the value is not there, ++ operator will assume it to be 0 (and then increment to 1).如果该值不存在,++ 运算符将假定它为 0(然后递增到 1)。 If it is already there - it will simply be incremented.如果它已经存在 - 它将简单地增加。
I guess that this code should answer your question:我想这段代码应该可以回答您的问题:
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";
}
Output: Output:
three: 1
one: 1
two: 2
The iteration can be simplified to:迭代可以简化为:
$hash{$_}++ for (@keys);
(See $_
in perlvar .) And you can even write something like this: (参见perlvar中的$_
。)你甚至可以这样写:
$hash{$_}++ or print "Found new value: $_.\n" for (@keys);
Which reports each key the first time it's found.哪个在第一次找到时报告每个密钥。
You can just go with:您只需 go 即可:
if(!$strings{$string}) ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.