开发者

About the usage of hash reference in Perl

开发者 https://www.devze.com 2023-03-26 14:33 出处:网络
This reports syntax error: $hash={a=>2}; print %{$hash}{a}; But 开发者_运维百科this works: print each(%{$hash})

This reports syntax error:

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

But 开发者_运维百科this works:

print each(%{$hash})

Why??


To get an element from a hashref, you take the normal code for getting a hash element: $foo{'bar'}, and replace the name of the hash, not including the sigil, with the hashref: $$hash{'bar'}. Your % would only be used to dereference to the full hash, as in your each case, not just an element.

More helpful hints at http://perlmonks.org/?node=References+quick+reference.


Maybe this will help you understand why it's wrong...

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


Yeah, just like print %hash{a} doesn't work even though each(%hash) does.

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


You were missing the lookup '->'.

print %{$hash}{a};

should be:

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

You declare it as $ but then try to cast to a hash and retrieve the value, not sure why.

Just retrieve like so:

print $hash->{a};

My personal preference when it comes to hashes:

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

Multi level:

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

Looping:

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

精彩评论

暂无评论...
验证码 换一张
取 消