Here's what I came up with... For each key in the structure, we provide the value we want for the default (if that key is missing). Then we work through the structure, replacing any undefined values with the desired default.

I'm not at all sure this is the kind of solution you want, (and I'm not entirely certain it even works like I think it does) but it was a lot of fun to tinker with it. :-)

use Data::Dumper; # Trying to guarantee this: #$self->{db}->{offer}->{product_id}->{name} # We start with a fully formed hashref $self->{db}->{offer}->{product_id}->{name} = 1; # and undef somewhere in the middle undef $self->{db}; # Show the structure just to prove it is too short print Dumper $self; my $Last = $self; for (['db',{}], ['offer',{}], ['product_id',&func], ['name',42]){ defined $Last->{$_->[0]} or $Last->{$_->[0]} = $_->[1]; $Last = $Last->{$_->[0]}; } print Dumper $self; # func() is the default for key 'product_id' above sub func{ {} }
prints:
$VAR1 = { 'db' => undef }; $VAR1 = { 'db' => { 'offer' => { 'product_id' => { 'name' => 42 } } } };

Russ
Brainbench 'Most Valuable Professional' for Perl


In reply to RE: undefs and functions by Russ
in thread undefs and functions by dlux

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.