关于Perl中哈希引用的用法

时间:2011-08-05 01:58:48

标签: perl

报告syntax error

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

但这有效:

print each(%{$hash})

为什么?

4 个答案:

答案 0 :(得分:5)

要从hashref获取元素,您可以使用正常代码获取哈希元素:$foo{'bar'},并使用hashref:$$hash{'bar'}替换哈希的名称(不包括sigil) 。您的%只会用于取消引用完整哈希值,就像在每种情况下一样,而不仅仅是元素。

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

答案 1 :(得分:3)

也许这会帮助你理解为什么这是错误的......

$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}

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

您错过了查找' - >'。

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'
}