![](/img/trans.png)
[英]PERL, comparing 2 hashes, list all keys and all values even if they are different
[英]perl hashes - comparing keys and values
我一直在阅读perl doc,但我无法理解哈希。 我试图找出是否存在哈希键,如果存在,则比较其值。 令我困惑的是,我的搜索说你发现if 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";
}
}
$files{$key}
确实会返回该键的值。 但是如果在布尔上下文中该值恰好是假的,比如0
或''
(空字符串)怎么办?
考虑这样的哈希:
my %foo = ( red => 42, blue => 0, green => '', yellow => undef );
如果我要说if ( $foo{blue} )
条件会失败。 即使哈希中存在blue
,条件也是假的,因为$foo{blue}
值为零。 与green
和yellow
键相同 - 空字符串和undef
是错误值。
如果没有exists
,就没有(简单的)方法来确定散列键实际上是否实际存在且其值是否为假,或者它根本不存在。 (你可以调用keys
然后grep
结果列表,但这太荒谬了。)
你的代码对我来说非常好。 您正确使用exists
。
exists $hash{key}
表示如果密钥存在,则defined $hash{key}
表示如果密钥存在且其值已定义,则$hash{key}
表示密钥是否存在且其值是否为true(请参阅http:// perldoc.perl.org/perlsyn.html#Truth-and-Falsehood )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.