http://qs1969.pair.com?node_id=25645


in reply to undefs and functions

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