Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found