2

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

有没有简单的方法来做到这一点?

4

2 回答 2

15

检查哈希键是否存在的方法是:

exists $hash{$key}
于 2009-07-27T14:26:23.153 回答
3

使用条件运算符可以让您在 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} 存在时使用 $hash{$PGkey}[$id] 并且如果不存在则回退到 $PGval,那么您可以说

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: $!";
于 2009-07-27T14:10:06.237 回答