Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Difference in accessing a Hash

by perl@1983 (Sexton)
on Aug 03, 2012 at 12:55 UTC ( #985226=perlquestion: print w/ replies, xml ) Need Help??
perl@1983 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have a hash as below:
my $a = { b => 1, c => 2, d => { e => 1 }, }
I wanted to know what is the difference when I access above hash using $a{b} vs $a->{b}? Thanks in advance.

Comment on Difference in accessing a Hash
Download Code
Re: Difference in accessing a Hash
by moritz (Cardinal) on Aug 03, 2012 at 13:03 UTC
    $a{b} accesses the hash %a, which has no relation to the variable $a. $a->{b} assumes that $a is a hash reference, and accesses the element b of it.

    Always use strict, it will catch such errors if you happen to write the wrong one (and the other one isn't declared).

      Got it. Thanks moritz for the clarification.
Re: Difference in accessing a Hash
by sundialsvc4 (Abbot) on Aug 03, 2012 at 13:37 UTC

    Also notice that $$foo{bar} ... notice the doubled dollar-sign ... is equivalent to $foo->{bar}.   The potential problem being of course that a single dollar-sign in this case is also syntactically valid but carries a different meaning.   The best thing to do is to adopt a “shop standard” and then stick to it very religiously.   “PARIS IN THE THE SPRING” and all of that ... heh ... you did see the extra word in there, now, didn’t you?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://985226]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2014-09-21 11:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls