The code I posted was based on code that did use :lvalue, but I adapted it to match the OP.

Original:

I strongly recommend using an existing solution such as Data::Diver.

use Data::Diver qw( DiveVal ); my @keys = map "level$_", 1 .. 3; my $branch = {}; DiveVal($branch, map \$_, @keys) = 'leaf'; -or- my %branch; DiveVal(\%branch, map \$_, @keys) = 'leaf';

Obviously, it can be done without module too.

sub DiveVal :lvalue { my $p = \shift; $p = \( $$p->{$_} ) for @_; $$p } my @keys = map "level$_", 1 .. 3; my $branch; DiveVal($branch, @keys) = 'leaf'; -or- my %branch; DiveVal(\%branch, @keys) = 'leaf';

How my DiveVal works:

Pre-loop: $p references $branch After loop pass 0: $p references $branch->{level1} After loop pass 1: $p references $branch->{level1}{level2} After loop pass 2: $p references $branch->{level1}{level2}{level3} Returned: $branch->{level1}{level2}{level3}

The extra level of indirection has many benefits.

Being fundamentally the same solution, the explanation applies to Merlyn's code too. Just substitute $a for $p, and it's a reference to the final scalar that's returned instead of the scalar itself as an lvalue.


In reply to Re^3: Recursively walk a hash to get to an element by ikegami
in thread Recursively walk a hash to get to an element by merlyn

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.