【问题标题】:About the usage of hash reference in Perl关于 Perl 中哈希引用的使用
【发布时间】:2011-08-05 21:11:50
【问题描述】:

此报告syntax error

$hash={a=>2};
print %{$hash}{a};

但这有效:

print each(%{$hash})

为什么??

【问题讨论】:

  • 不是问题的直接答案,但print $hash->{a}; 有效。

标签: perl


【解决方案1】:

要从 hashref 中获取元素,请使用获取 hash 元素的普通代码:$foo{'bar'},并将不包括 sigil 的 hash 名称替换为 hashref:$$hash{'bar'}。您的 % 将仅用于取消引用完整哈希,就像在您的每种情况下一样,而不仅仅是一个元素。

更多有用的提示http://perlmonks.org/?node=References+quick+reference

【讨论】:

    【解决方案2】:

    也许这会帮助你理解错误的原因......

    $hash = {a => 2};     #Works: $hash is a reference to the hash
    %foo  = %{$hash};     #Now, we've dereferenced the hash to %foo
    
    # Wherever we have "$hash", we can now use "foo"...
    
    print %foo{a};        #Whoops! Doesn't work. 
    print %hash{a};       #And, neither did this!
    
    print $foo{a};        #No problem! Use '$" when talking about a single hash element
    print ${$hash}{a}     #Same as above.
    
    print each %foo;      #Each takes a hash (with "%" sign)
    print each %{$hash};  #Same as above.
    
    print $hash->{a}      #Syntactic Sugar: Same as ${$hash{a}} or $$hash{a}
    

    【讨论】:

      【解决方案3】:

      是的,就像 print %hash{a} 不起作用,即使 each(%hash) 起作用。

      each(%hash)      ==>  each(%{ $ref })
      print($hash{a})  ==>  print(${ $ref }{a})
      

      【讨论】:

        【解决方案4】:

        您缺少查找“->”。

        print %{$hash}{a};
        

        应该是:

        print %{$hash}->{a};
        

        您将其声明为 $,但随后尝试强制转换为哈希并检索该值,但不知道为什么。

        像这样检索:

        print $hash->{a};
        

        我个人对哈希的偏好:

        $hash1->{a} = 1;
        print $hash1->{a}, "\n"; # prints '1'
        

        多层次:

        $hash2->{a}{a} = 1;
        $hash2->{a}{b} = 2;
        print $hash2->{a}{a}, "\n"; # prints '1'
        print $hash2->{a}{b}, "\n"; # prints '2'
        

        循环:

        while (my ($key, $value) = each %{$hash1})
        {
            print $key, "\n"; # prints 'a'
            print $value, "\n"; # prints '1'
        }
        

        【讨论】:

        • print %{$hash}->{a}; 实际上是无效的,尽管它偶然工作了很长时间。在最近的 perls 上,它会给出警告“不推荐使用哈希作为参考”
        猜你喜欢
        • 2012-09-21
        • 1970-01-01
        • 2012-06-01
        • 1970-01-01
        • 2014-04-13
        • 2011-09-29
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        相关资源
        最近更新 更多