bcrowell2 has asked for the wisdom of the Perl Monks concerning the following question:
O Monks,
The following code shows three ways of indexing into a hash of hash references.
perl -e '%x = (1=>{3=>4}); print $x{1}->{3}' perl -e '%x = (1=>{3=>4}); print $x{1}{3}' perl -e '%x = (1=>{3=>4}); $r= $x{1}; print $r{3}'
The first one is the way I'm used to doing it, and it seems logical to me because $x{1} is a reference to a hash, not a hash, so you ought to use the -> to dereference it. However, I came across he second syntax in a cpan module, and when I looked in the camel book, this was actually the syntax presented there. Surprisingly (to me), it produced the same result. It seemed to me like it shouldn't work, because $x{1} is a reference, and you can't normally index into a hash via a reference without the ->. The third example doesn't work, which is what I expected.
Can anyone explain why syntax #2 works, while #3 doesn't? It seems like #3 is just doing the same thing as #2, but in two steps. Is this an exception that's built into the perl interpreter as a special case somewhere, or is there something I'm not understanding that makes this a regular usage?
TIA! -Ben
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: $x{1}{2} versus $x{1}->{2}
by kennethk (Abbot) on Jan 16, 2009 at 17:04 UTC | |
|
Re: $x{1}{2} versus $x{1}->{2}
by jettero (Monsignor) on Jan 16, 2009 at 17:01 UTC | |
|
Re: $x{1}{2} versus $x{1}->{2}
by jethro (Monsignor) on Jan 16, 2009 at 17:15 UTC | |
|
Re: $x{1}{2} versus $x{1}->{2}
by sgt (Deacon) on Jan 16, 2009 at 17:37 UTC | |
|
Re: $x{1}{2} versus $x{1}->{2}
by mr_mischief (Monsignor) on Jan 16, 2009 at 17:36 UTC |