You can find some previous discussion of this question in A hash slice but not...

Here's an updated form of my code example from that discussion:

use strict; sub nested_value { my $href = shift; my $keys = shift; my $last_key = pop @$keys; for my $key (@$keys) { $href = $href->{$key} ||= {}; } if (@_) { $href->{$last_key} = shift; } return $href->{$last_key}; } my %hash; nested_value(\%hash, [qw/one two three/], 1); print nested_value(\%hash, [qw/one two three/]), "\n"; use Data::Dumper; print Dumper \%hash;
This subroutine can be used to set and get the value. If there's a third argument to the subroutine, it's set as the new value for the keys; either way the value for the keys is returned.

Note that this code assumes that each key will either point to a hash reference or to a value. If you set a value first, and then try to use it as a nested hash, you'll get an error from use strict. If you set a nested hash first, and then set a value at the same level, you'll delete the entire nested hash. Error checking could be added to the sub to handle those situations gracefully.


In reply to Re: How do I populate a ML hash from an array? by chipmunk
in thread How do I populate a ML hash from an array? by unixdown

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.