Eth*_*her 27
exists()和defined()似乎不适用于这种情况,他们只是看看给定键的值是否未定义,他们不检查哈希是否实际具有键
不正确.这确实是defined()做什么的,但exists()确实是你想要的:
my %hash = (
key1 => 'value',
key2 => undef,
);
foreach my $key (qw(key1 key2 key3))
{
print "\$hash{$key} exists: " . (exists $hash{$key} ? "yes" : "no") . "\n";
print "\$hash{$key} is defined: " . (defined $hash{$key} ? "yes" : "no") . "\n";
}
Run Code Online (Sandbox Code Playgroud)
生产:
$hash{key1} exists: yes
$hash{key1} is defined: yes
$hash{key2} exists: yes
$hash{key2} is defined: no
$hash{key3} exists: no
$hash{key3} is defined: no
为这两个函数的文档可在命令行perldoc -f defined和perldoc -f exists(或阅读文档在所有方法perldoc perlfunc*).官方网站文档在这里:
*由于您特别提到了RTFM并且您可能不了解Perl文档的位置,因此我还要指出您可以perldoc perl在http://perldoc.perl.org上获取所有perldoc的完整索引.
FMc*_*FMc 11
如果我正确地阅读你的问题,我认为你对存在感到困惑.从文档:
存在EXPR
给定一个指定哈希元素或数组元素的表达式,如果哈希或数组中的指定元素已被初始化,则返回true,即使相应的值未定义.
例如:
use strict;
use warnings;
my %h = (
foo => 1,
bar => undef,
);
for my $k ( qw(foo bar baz) ){
print $k, "\n" if exists $h{$k} and not defined $h{$k};
}
Run Code Online (Sandbox Code Playgroud)
简短回答:
if ( exists $hash{$key} and not defined $hash{$key} ) {
...
}
Run Code Online (Sandbox Code Playgroud)