Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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.

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://985226]
Approved by moritz
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2018-06-19 09:30 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (112 votes). Check out past polls.