in reply to HoHoH Dynamicaly

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