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


In reply to $x{1}{2} versus $x{1}->{2} by bcrowell2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.