加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:50:49 所属栏目:大数据 来源:网络整理
导读:我需要确定Perl哈希是否具有给定键,但该键将映射到undef值.具体来说,这样做的动机是在使用带有散列引用的getopt()时看到布尔标志.我已经搜索了这个网站和谷歌,而且exists()和defined()似乎不适用于这种情况,他们只是看看给定键的值是否未定义,他们不检查是否
我需要确定Perl哈希是否具有给定键,但该键将映射到undef值.具体来说,这样做的动机是在使用带有散列引用的getopt()时看到布尔标志.我已经搜索了这个网站和谷歌,而且exists()和defined()似乎不适用于这种情况,他们只是看看给定键的值是否未定义,他们不检查是否哈希实际上有关键.如果我是RTFM,请指出解释此问题的手册.

解决方法

exists() and defined() don’t seem to be applicable for the situation,they just see if the value for a given key is undefined,they don’t check if the hash actually has the key

不正确.这确实是define()的作用,但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 defined和perldoc -f exists(或者阅读perldoc perlfunc *中所有方法的文档).官方网站文档在这里:

> http://perldoc.perl.org/functions/exists.html
> http://perldoc.perl.org/functions/defined.html

*由于您特别提到了RTFM并且您可能不知道Perl文档的位置,我还要指出您可以在perldoc perl或http://perldoc.perl.org获得所有perldoc的完整索引.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读