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

时间:2022-02-18 23:44:56

This question already has an answer here:

这个问题在这里已有答案:

I want to check if parameter $PGkey is equal to a key with the same name inside a hash table. Further, I want to do it in a format as close to this as possible:

我想检查参数$ 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";
    }
}

Is there a simple way to do it?

有一个简单的方法吗?

2 个解决方案

#1


Using the conditional operator lets you factor out the common code in that if/else statement:

使用条件运算符可以将if / else语句中的公共代码分解出来:

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

Or if you just misstated the problem and really want to use $hash{$PGkey}[$id] if $hash{$PGkey} exists and fall back to $PGval if it doesn't, then you can say

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

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

A quick note, you seem to be using the old bareword style filehandles. The new (if ten years old can be considered new) lexical filehandles are superior in every way:

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

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

#2


The way to check for hash key existence is:

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

exists $hash{$key}

#1


Using the conditional operator lets you factor out the common code in that if/else statement:

使用条件运算符可以将if / else语句中的公共代码分解出来:

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

Or if you just misstated the problem and really want to use $hash{$PGkey}[$id] if $hash{$PGkey} exists and fall back to $PGval if it doesn't, then you can say

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

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

A quick note, you seem to be using the old bareword style filehandles. The new (if ten years old can be considered new) lexical filehandles are superior in every way:

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

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

#2


The way to check for hash key existence is:

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

exists $hash{$key}