Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

given a list ( hashREF, ..., hashVAL ) where the ... contains a variable number of hashKEYS.

so i want the result to look like :

$hashREF->{$key0}->{$key1}->{$key2} = $hashVAL
this snippet of code doesn't work. why?
my $list = [ "k0", "k1", "k2", ]; my ($h,$t); foreach my $k ( @$list ) { $h->{$k} = {}; $h = $h->{$k}; } $h = $val;

thanks

Replies are listed 'Best First'.
Re: adding keys to a hash
by kyle (Abbot) on Mar 29, 2008 at 02:14 UTC

    It doesn't work because your loop walks down a chain of hash references, but you don't retain the first reference in the chain anywhere, and at the end of the loop, you clobber the reference you have ($h) with some (presumably plain) scalar value ($val).

    I made some changes.

    use Data::Dumper; my $list = [ "k0", "k1", "k2", ]; my ($h,$t); $t = $h = {}; foreach my $k ( @{$list}[ 0 .. $#{$list}-1 ] ) { $t->{$k} = {}; $t = $t->{$k}; } $t->{$list->[-1]} = 'val'; print Dumper $h; __END__ $VAR1 = { 'k0' => { 'k1' => { 'k2' => 'val' } } };

    Having gone through all that, however, you might want to look into Data::Diver for this kind of thing.

Re: adding keys to a hash
by Fletch (Bishop) on Mar 29, 2008 at 02:15 UTC

    For that code in and of itself you don't keep a reference to the top / first hash so you've no way to get back the entire constructed value. Having said that, perhaps Data::Diver might do what you want off the shelf?

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.