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
-
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.