abhy has asked for the wisdom of the Perl Monks concerning the following question:

I am confused with the syntax used to dereference a hash, when the reference is obtained from a hash(or array) and when there is a direct reference.

Consider this code snippet:

my $ref = {"one" => "1"}; my %hash = ("ref" => $ref); my @array = ($ref); print "Array:", $array[0]{"one"}, "\n"; print "Hash:", $hash{"ref"}{"one"}, "\n"; print "Ref:", $$ref{"one"}, "\n";

When the reference is taken from a hash or array it is preceded by just a single sigil that of the array or hash, but when it is a direct reference it is preceded by a double sigil.

In the above snippet is it not $ref that I get when I do $array[0]? Since I have $ref with me, should I not use another sigil to reference the value stored in the hash as is done with a direct reference?

Replies are listed 'Best First'.
Re: Hash dereferencing
by targetsmart (Curate) on Mar 05, 2009 at 06:35 UTC
    ideally you have to dereference like this
    print "Array:", $array[0]->{"one"}, "\n"; print "Hash:", $hash{"ref"}->{"one"}, "\n"; print "Ref:", $ref->{"one"}, "\n";
    but in perl -> is optional when dereferencing hash reference(considering your case) so it works.
    one more example for you
    my $a = { a => { b => { c => ['d'] } }}; print ">",$a->{'a'}->{'b'}->{'c'}->[0],"<\n"; print ">",$a->{'a'}{'b'}{'c'}[0],"<\n";
    both the lines print 'd'
    from perlreftut manual
    Arrow Rule In between two subscripts, the arrow is optional. Instead of $a[1]->[2], we can write $a[1][2]; it means the same + thing. Instead of "$a[0]->[1] = 23", we can write "$a[0][1] = 23"; it means the same thing. Now it really looks like two-dimensional arrays!

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: Hash dereferencing
by chromatic (Archbishop) on Mar 05, 2009 at 06:38 UTC
    ... when it is a direct reference it is preceded by a double sigil.

    That's to disambiguate between a scalar $ref containing a hash reference and a hash %ref. Think about that for a while and you'll understand.

Re: Hash dereferencing
by abhy (Novice) on Mar 06, 2009 at 06:51 UTC
    Thanks monks.