Perl:如何测试是否已将任何值(甚至为零)分配给散列键

use*_*889 3 perl hash

是否有正确的测试方法,如果已经为特定的哈希键分配了任何值,即使该值为零?我一直在处理这样的声明:

%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }
Run Code Online (Sandbox Code Playgroud)

但是,对于已被触摸的键和已赋值为0的键(例如,$ hash {b}和$ hash {c}都计算为'false'),这会产生相同的结果.有没有办法说出这两者之间的区别?

zel*_*lio 9

使用定义的运算符检查某些内容是否具有非值的值undef

if ( defined $hash{ $key } ) {
  //do stuff
}
Run Code Online (Sandbox Code Playgroud)

使用exists运算符检查是否已写入$keya%hash

if ( exists $hash{ $key } ) {
  //do stuff
}
Run Code Online (Sandbox Code Playgroud)

不同之处在于defined检查一个值是否是除了以外的任何值undef以及exists用于验证是否$key是哈希值的关键字.


zou*_*oul 5

perldoc -f definedperldoc -f exists:

my %hash = (foo => 0, bar => undef);

print defined $hash{foo}; # true
print defined $hash{bar}; # false
print exists $hash{bar};  # true
print exists $hash{baz};  # false

delete $hash{bar};
print exists $hash{bar};  # false
Run Code Online (Sandbox Code Playgroud)

  • "存在"是指Key."定义"是指价值. (2认同)