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

Hi, I hava the following code.
foreach $key(sort {$a<=>$b} keys(%resultHoA)){ @tmp=@{$resultHoA{$key}};#[@sorted_cols]; $statushash{$tmp[0]}{$tmp[1]}{$tmp[2]}[0]='0'; }
In the above code the keys ({$tmp[0]}{$tmp[1]}{$tmp[2]}) are three. How can I change this code so that the no of keys can match the element of the array?. ie. if only one elt then hash must be
$statushash{$tmp[0]}[0]='0',
if @tmp contains 2 elts hash mush be
$statushash{$tmp[0]}{$tmp[1]}[0]='0'
and so on. Can U help me out?. Thanks in Adv.

Replies are listed 'Best First'.
Re: HoHoH Dynamicaly
by brian_d_foy (Abbot) on Dec 06, 2006 at 06:31 UTC

    The trick is to work from the inside-out. Define the lowest level, then add that to the next level. Inside the foreach, I can use $hash on both sides of the assignment because Perl will compute the right hand side first then assign that result to the left-hand side.

    my @tmp = qw( a b c d ); my @keys = reverse @tmp; my $first_key = shift @keys; my $hash = { $first_key => [ 0 ] }; foreach my $key ( @keys ) { $hash = { $key => $hash }; } use Data::Dumper; print Dumper( $hash );

    Rael Dornfest asked me to do this for bloxsom, and I thought I had posted it somewhere but I can't find it now.

    You can make it simpler sometimes by putting the leaf value as the initial value for $hash, then letting the foreach construct all the levels of the hash. It's a bit cleaner, but harder to see the trick:

    my @tmp = qw( a b c d ); my $hash = [0]; # not really a hash foreach my $key ( reverse @tmp ) { $hash = { $key => $hash }; } use Data::Dumper; print Dumper( $hash );
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
Re: HoHoH Dynamicaly
by ikegami (Patriarch) on Dec 06, 2006 at 05:12 UTC
Re: HoHoH Dynamicaly
by Roy Johnson (Monsignor) on Dec 06, 2006 at 18:16 UTC
Re: HoHoH Dynamicaly
by Anonymous Monk on Dec 06, 2006 at 12:04 UTC
    my $ref = \%statushash; $ref = $ref->{$_} for @tmp; $ref->[0] = '0';