Here below is a generic way to get the value from arbitrary nestled keys:
sub get_hash_key { my ($h, @keys) = @_; my $v = $h; $v = $v->{$_} foreach @keys; return $v; }
But this isn't so useful if we want to change the data. So instead we want to return a reference to the value:
sub get_hash_key_ref { my ($h, @keys) = @_; my $r = \$h; $r = \$$r->{$_} foreach @keys; return $r; }
(Please note that we can't just take &get_hash_key and make the last line return \$v.)

This technique has several advantages over the other common way (using ||= {}). One is simplicity. In this you do all the logic in one statement and you don't have to make an exception for the last key. Another is that you let perl to the autovivifying for you, so you don't even have to check for bad values. If there is a defined value that isn't a hash references you'll be notified with a (not-so-nice?) error message. This behaviour, I believe, is the most analogous behaviour you can find to doing a hardcoded dereference (overlooking eval EXPR), but I shouldn't say too much--it always turns out I missed something. :)

Cheers,
-Anomo

In reply to Re: Recursive hash assignment by Anonymous Monk
in thread Recursive hash assignment by Tanalis

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.