Adding some syntactic sugar with prototype and lvalue (not sure when the + prototype was introduced UPDATE: 5.14.0 code corrected)

Checking the ref-type would help diving arrays too. (but would probably reinvent Data::Diver )

use v5.14; use warnings; use Test::More; sub dive(+;@) :lvalue { my $h = \ shift; $h = \($$h->{$_}) for @_; $$h; } my %hsh; my $h_ref = \%hsh; my $val = $hsh{a}{b}{c} = 3; my $val2 = 42; my @path = qw/a b c/; my $test; ;;;;;;;;;; $test = "Prototypes"; is( dive(%hsh => @path) , $val, "$test accepts \%list form"); is( dive($h_ref=> @path) , $val, "$test accepts \$ref form"); ;;;;;;;;;; $test = "assign directly to lvalue"; dive(%hsh=> @path) = $val2; is( $hsh{a}{b}{c}, $val2, $test); ;;;;;;;;;; $test = "increment in place"; dive( %hsh=> @path )++; is( $hsh{a}{b}{c}, ++$val2, $test); ;;;;;;;;;; $test = "grab scalar reference"; my $s_ref = \ dive(%hsh, @path); $$s_ref++; is( $hsh{a}{b}{c}, ++$val2, $test); ;;;;;;;;;; $test = "aliasing"; for my $alias ( dive(%hsh, @path) ) { $alias++; } is( $hsh{a}{b}{c}, ++$val2, $test); done_testing;
OUTPUT:
ok 1 - Prototypes accepts %list form ok 2 - Prototypes accepts $ref form ok 3 - assign directly to lvalue ok 4 - increment in place ok 5 - grab scalar reference ok 6 - aliasing 1..6

UPDATE: cosmetic corrections

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery


In reply to Re^2: Recursively walk a hash to get to an element by LanX
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.