如何确定Perl哈希是否包含映射到未定义值的键?

Ale*_*all 8 perl hash key exists defined

我需要确定Perl哈希是否具有给定密钥,但该密钥将映射到undef值.具体来说,这样做的动机是看到布尔标志在使用getopt()哈希引用时是否传入其中.我已经搜查两本网站和谷歌,exists()defined()似乎不适用的情况下,他们只看到如果给定键的值是不确定的,他们不检查哈希实际上有钥匙.如果我是RTFM,请指出解释此问题的手册.

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 definedperldoc -f exists(或阅读文档在所有方法perldoc perlfunc*).官方网站文档在这里:

*由于您特别提到了RTFM并且您可能不了解Perl文档的位置,因此我还要指出您可以perldoc perlhttp://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)


Ada*_*edy 6

简短回答:

 if ( exists $hash{$key} and not defined $hash{$key} ) {
    ...
 }
Run Code Online (Sandbox Code Playgroud)