【问题标题】:Why is testing if a key exists in a hash not working for ref to hash?为什么测试哈希中是否存在密钥对引用哈希不起作用?
【发布时间】:2012-04-13 08:34:25
【问题描述】:

当我引用哈希时,如何判断一个键是否存在于一个 has 中?以下内容看似简单明了(以我的专业水平),但打印出的结果与预期不同:

%simple = (a => 8, b=> 9);
print  0+exists $simple{a},  0+exists $simple{c},   "\n";    # prints 10

%href = \%simple;
print  0+exists $href{a},  0+exists $href{c},  "\n";        # expect fail; bad syntax
print  0+exists $href->{a},  0+exists $href->{c},  "\n";    # should work
print  0+exists ${$href}{a},  0+exists ${$href}{c},  "\n";  #  should work
print  0+exists $$href{a},  0+exists $$href{c},  "\n";      # not sure

# see if attempt to ask about {c} accidently created it
print %simple, "\n";

打印出来

10
00
00
00
00
a8b9

我期望(非常乐观):

10
10
10
10
10
a8b9

我并不期望我尝试的所有工作方式,但至少应该有一种方式。我已经检查了 perldoc、其他 SO 问题和谷歌搜索,我想出的只是我在其中一些行中使用的语法应该可以工作。

【问题讨论】:

    标签: perl hash reference exists


    【解决方案1】:

    线

    %href = \%simple;
    

    没有做你认为它做的事; perl -w(或use warnings;)会给你一个关于奇数个散列元素的警告,这应该足以暗示它试图做什么(如果你仔细想想,为什么你的“错误语法”不是)。试试

    $href = \%simple;
    

    另外,学习使用use warnings;use strict;,并且始终使用它们。

    【讨论】:

    • 啊哈,我以前做过那个嘘声。是的,即使是非常短的实验,严格和警告也适用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多