如何检查Perl中的哈希中是否存在密钥?

时间:2009-07-27 13:43:06

标签: perl hash exists

我想检查参数$PGkey是否等于哈希表中具有相同名称的键。此外,我希望尽可能接近这种格式:

while(<PARAdef>) {
    my($PGkey, $PGval) = split /\s+=\s+/;
    if($PGkey == $hash{$PGkey}) {
        print PARAnew "$PGkey = $hash{$PGkey}->[$id]\n";
    } else {
        print PARAnew "$PGkey = $PGval\n";
    }
}

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:15)

检查哈希密钥存在的方法是:

exists $hash{$key}

答案 1 :(得分:3)

使用conditional operator可以将if / else语句中的公共代码分解出来:

while ( <PARAdef> ) {
    chomp;
    my ($PGkey, $PGval) = split /\s+=\s+/;
    print "$PGkey = ",
        $PGval eq $hash{$PGkey}[$id] ? $hash{$PGkey}[$id] : $PGval, "\n";
}

或者如果你只是误解了这个问题并且真的想要使用$ hash {$ PGkey} [$ id]如果$ hash {$ PGkey}存在并且如果不存在则回退到$ PGval,那么你可以说< / p>

while ( <PARAdef> ) {
    chomp;
    my ($PGkey, $PGval) = split /\s+=\s+/;
    print "$PGkey = ",
        $PGkey ne "def" and exists $hash{$PGkey} ?
            $hash{$PGkey}[$id] : $PGval, "\n";
}

快速说明,您似乎正在使用旧的裸字样式文件句柄。新的(如果十年之久可以被认为是新的)词汇文件句柄在各方面都是优越的:

open my $PARAdef, "<", $filename
    or die "could not open $filename: $!";