【问题标题】:perl hashes - comparing keys and valuesperl 哈希 - 比较键和值
【发布时间】:2010-04-18 07:47:30
【问题描述】:

我一直在阅读 perl 文档,但我无法完全理解哈希。我正在尝试查找是否存在哈希键,如果存在,请比较其值。让我感到困惑的是,我的搜索结果表明您发现 if (exists $files{$key}) 是否存在密钥,但 $files{$key} 也给出了值?我正在处理的代码是:

foreach my $item(@new_contents) {
    next if !-f "$directory/$item";
    my $date_modified = (stat("$directory/$item"))[9];

    if (exists $files{$item}) {
        if ($files{$item} != $date_modified {
            $files{$item} = $date_modified;
            print "$item has been modified\n";
        }
    } else {
        $files{$item} = $date_modified;
        print "$item has been added\n";
    }
}

【问题讨论】:

    标签: perl


    【解决方案1】:

    $files{$key} 确实会返回该键的值。但是,如果该值在布尔上下文中恰好为 false,例如 0''(空字符串)怎么办?

    考虑这样的哈希:

    my %foo = ( red => 42, blue => 0, green => '', yellow => undef );
    

    如果我说if ( $foo{blue} ),条件将失败。尽管blue 存在于哈希中,但条件为假,因为$foo{blue} 的值为零。与greenyellow 键相同——空字符串和undef 是假值。

    如果没有exists,就没有(简单的)方法可以确定哈希键是否确实存在并且其值为假,或者根本不存在。 (你可以调用keys 然后grep 结果列表,但这太荒谬了。)

    您的代码在我看来非常完美。您正在正确使用exists

    【讨论】:

    • @friedo 我意识到是一些语法错误给我带来了问题,但感谢您的澄清,让事情变得更加清晰!
    【解决方案2】:

    exists $hash{key} 表示键是否存在,defined $hash{key} 表示键是否存在且其值已定义,$hash{key} 表示键是否存在且其值为 true(参见 http://perldoc.perl.org/perlsyn.html#Truth-and-Falsehood)。

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2013-10-17
      相关资源
      最近更新 更多