Your code is pretty close, but I'm afraid you need another level of referencing to deal with autovivifying. I'll try to explain why... Consider when you have an empty $DATA{3}{h} and call put_element($DATA{3}, 'h', 'i', "worked"). Then your code eventually does: That last line autovififies the undef in $current to a fresh anonymous hashref, fetches the key 'i' from the new anonymous hash (which returns undef), and sets $current to this undef... But overwriting the value of $current cleans up the anonymous hash that was just created. It's lost forever. Whoops!

Instead of this, you need to keep another level of references. Now instead of trying to keep the values of $DATA{3}, $DATA{3}{h}, $DATA{3}{h}{i} (which are copied, so don't do the right thing if the hash key doesn't exist), we have to keep references to those slots of the hashes. This way the new hashes can be autovivified in the appropriate slot, and not into your temporary variable.

You also need to use $_[0] instead of shift if the first argument has a hash dereference that may be autovifified (since shift makes a copy, but $_[0] is an alias to the first arg, not a copy).

sub put_element { my $current = \ $_[0]; shift; my $value = pop; $current = \ $$current->{ +shift } while @_; $$current = $value; } use Data::Dumper; my %DATA; put_element( $DATA{3}, 'h', 'i', "Worked" ); ## $DATA{3} autovifified + too put_element( $DATA{3}, 'b', 'y', 'e' ); ## $DATA{3} exists print Dumper \%DATA;
Yes, the autovivification makes this a very sticky situation. But if you can understand this, you are in very good shape with your understanding of references.

blokhead


In reply to Re: Missing something with regards to references by blokhead
in thread Missing something with regards to references by scottb

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.