Sometimes with these "what am I missing" type of questions, the best approach is to explain how I'd do it, and then see if that answer somehow hits the one thing you need to understand.

Lets start with the function usage model: You suggest

put_element( $DATA{3}, 'h', 'i', 'worked' );
For clarity, lets do the whole hash. You can create a reference to the top level (root) hash using the backslash operator:
put_element( \%DATA, 3, 'h', 'i', 'worked' );
All those quotes get tiresome after a while, so lets get rid of them:
put_element( \%DATA, qw(3 h i worked) );
Perl flattens arg-lists, so that is identical to the previous version.

So now the implementation (I'll omit the error-checks):

sub put_element { my ($hashref, @path) = @_; # The leaf node and its value are special my $value = pop @path; my $leaf = pop @path; # walk the tree, create non-existing nodes for my $node (@path) { $hashref = $hashref->{$node} ||= {}; } # Finally, set the value at the leaf $hashref->{$leaf} = $value; }
Hopefully the comments are sufficient to explain my thinking.

--Dave
Opinions my own; statements of fact may be in error.

In reply to Re: Missing something with regards to references by dpuu
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.