如何查看Perl哈希是否已经有某个键?

54 lookup perl hash key

我有一个Perl脚本,它计算文本文件中各种字符串的出现次数.我希望能够检查某个字符串是否还不是散列中的键.是否有更好的方法完成这项工作?

这是我在做的事情:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

cpj*_*eur 114

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

if (exists $strings{$string}) {
    ...
} else {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,perl将自动生成多维哈希中不存在的任何中间密钥,以便"检查"您在最后一个哈希中查找的密钥是否存在.像这个例子这样的简单哈希不是问题但是......我的%test =(); 打印"bar"if(exists $ test {'foo'} {'bar'}); #perl只是自动验证了foo键,以便查找条形码"foo现在存在,你可能没想到!" if(exists $ test {'foo'}); (23认同)

RET*_*RET 10

我会反对使用,if ($hash{$key})因为如果密钥存在但它的值为零或为空,它将不会按预期执行.


小智 9

那么,您的整个代码可以限制为:

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

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

  • 虽然您的答案是正确的,但它确实回答了有关哈希的问题。 (2认同)

zou*_*oul 6

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

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";
}
Run Code Online (Sandbox Code Playgroud)

输出:

three: 1
one: 1
two: 2
Run Code Online (Sandbox Code Playgroud)

迭代可以简化为:

$hash{$_}++ for (@keys);
Run Code Online (Sandbox Code Playgroud)

(见$_perlvar).你甚至可以写出这样的事情:

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

它会在第一次发现时报告每个密钥.