For a specific case, you can just use the snippet you showed, of course: $hash{a}{b}{c}='some value'; When you specify nested references like that, Perl will autovivify the references that don't already point to something. (See perlref for more on autovivification.)

If you're looking to do this with an arbitrary list, here's a subroutine that shows one way to do it:

#!/usr/local/bin/perl -w use strict; sub set_nested_value { my($href, $keys, $value) = @_; my $last_key = pop @$keys; for my $key (@$keys) { $href = $href->{$key} ||= {}; } $href->{$last_key} = $value; } my %hash; set_nested_value(\%hash, ['a' .. 'c'], 'some value'); set_nested_value(\%hash, ['a', 'b', 'd'], 'other value'); use Data::Dumper; print Dumper \%hash;
The for loop descends through the nested hashes. With the ||= operator, when there isn't already a hash reference at that level, it creates a new anonymous hash. $href is then reassigned to the next level in the nested hash.

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: A hash slice but not.. by chipmunk
in thread A hash slice but not.. by smferris

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.