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

I've been doing some reading on perl and I'm confused about the -> operator.

sometimes I see people do this on a hash...

$x{a}->{b}= 'c';

...and sometimes this...

$x{a}{b} = 'c';

... but they appear to do the same thing.
I even ran both examples through Data::Dumper and the output is the same.
Is there any difference?
Should I use one over the other?

Replies are listed 'Best First'.
Re: dereference syntax
by hv (Prior) on Feb 26, 2003 at 18:26 UTC

    The two are identical: perl specifically allows $x{a}{b} as shorthand for $x{a}->{b}. Which you use is a matter of personal preference or house style.

    Note that this shorthand is available only for the second (or subsequent) dereference: $x{a} and $x->{a} are different, the first looking up a key in the hash %x while the second looks up a key in the hash reference $x.

    Hugo
Re: dereference syntax
by grantm (Parson) on Feb 26, 2003 at 18:30 UTC

    They are the same, you should use whichever you prefer. Some people think the arrow makes it clearer that you're dealing with a reference. Some people think it's visual noise.

    You can also omit the arrow when dereferencing a nested array (eg: $s{a}[1]).

    There is one thing to watch out for though. In your case, you have a hash called %x. If you had a hashref $x instead then the initial arrow would not be optional. You'd need to use either $x->{a}{b} or $$x{a}{b}.

Re: dereference syntax
by Zaxo (Archbishop) on Feb 26, 2003 at 18:29 UTC

    There is no difference: that is a bit of syntactic sugar for multilevel data structures. All such structures in perl are built from references, so the compiler doesn't need the arrow to know that dereference is needed.

    After Compline,
    Zaxo

Re: dereference syntax
by Mr_Person (Hermit) on Feb 26, 2003 at 20:42 UTC

    To quote the camel book, "The arrow is optional between brackets or braces, or between a closing bracket or brace and a parenthesis for an indirect function call."

    So basically it's whatever you prefer. I like to leave the arrow out because it's less to type, but if you think it looks better to leave it in, that works too.

Re: dereference syntax
by OM_Zen (Scribe) on Feb 26, 2003 at 19:55 UTC
    Hi ,

    # The $x is a hashreference and here : my $ones = {}; $ones{a}={b=>1}; print "[$ones{a}]\n"; print "[$ones->{a}]\n"; print "[$ones{a}->{b}]\n"; print "[$ones{a}{b}]\n"; __END__ [HASH(0xe01d8)] [] [1] [1]


    $x->{a} is not the same as $x{a}

    ( $x->{a} will be a lookup of the key of a hashrefernce (the declaration in the above my $ones = {} kind of decalaration available ),

    $x{a} will be a lookup of the key of %x)

    $x{a}->{$b} is the same as $x{a}{$b}

    Please read the perldoc perldsc for all kinds of data structure decalaration definition and access