roboticus++: Interesting, so at each iteration of the while loop it autovivifies the next key and you end up with a reference to the final memory location.

# As long as we have multiple keys, access the next subhash while (@keys > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; }

Should that be @keylist instead of @keys?

while (@keylist > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; }

Update: I just tried this and it doesn't work. $hashref = $hashref->{$key}; doesn't set anything in the hash and doesn't autovivify. I end up with an empty hash.

use strict; use warnings; use Data::Dump; my %testhash; my $hr = \%testhash; my $count = 0; while(<DATA>) { print "[", join('-',split ' ', $_), "]\n"; add_val( $hr, ++$count, split ' ', $_); } dd \%testhash; sub add_val { my ($hashref, $val, @keylist) = @_; die "Expected a list of keys!" unless @keylist; die "Expected a hashref!" unless "HASH" eq ref $hashref; # As long as we have multiple keys, access the next subhash while (@keylist > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; } # Now set the value $hashref->{shift @keylist} = $val; } __DATA__ a1 a2 a3 jjj kkk lll mmm Output: [a1-a2-a3] [jjj-kkk-lll-mmm] {}

Update again: With the addition of the subhash from your update it works. Thanks.

Output: [a1-a2-a3] [jjj-kkk-lll-mmm] { a1 => { a2 => { a3 => 1 } }, jjj => { kkk => { lll => { mmm => 2 } } }, }

In reply to Re^2: define a hash-value, using hash-ref and a list of keys by Lotus1
in thread define a hash-value, using hash-ref and a list of keys by janssene

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.