2010-01-23 58 views
7

我需要确定一个Perl哈希是否有给定的键,但该键将映射到一个undef值。具体而言,这样做的动机是在使用getopt()传递给它的散列引用时看到布尔标志。我已经搜索了这个网站和谷歌,exists()defined()似乎并不适用于这种情况,他们只是看看给定的密钥的值是不确定的,他们不检查哈希是否真的有键。如果我在这里是RTFM,请将我指向解释这个的手册。如何确定Perl哈希是否包含映射到未定义值的键映射?

回答

26

存在()和()定义似乎并不适用于该情况,他们只看到如果给定键的值是不确定的,他们不要检查散列实际上是否有密钥

不正确。这确实是什么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"; 
} 

生产:

 
$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得到所有perldocs的完整索引。

11

如果我正确地阅读你的问题,我认为你对exists感到困惑。从文档:

存在EXPR

鉴于指定 散列元件或数组元素的表达式,返回 真,如果在 散列或数组中指定的元件送子 初始化,即使相应的 值是未定义的。

例如:

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}; 
} 
6

简短的回答:

if (exists $hash{$key} and not defined $hash{$key}) { 
    ... 
}