http://qs321.pair.com?node_id=747216


in reply to Building an arbitrary-depth, multi-level hash

It's a little tricky, but not hard once you've seen it done once:

my %hash; my $value = "foo"; my @cats = qw(a b c d); my $p = \%hash; foreach my $item (@cats) { $p->{$item} ||= {}; $p = $p->{$item}; } $p->{_val} = $value; use Data::Dumper; print Dumper(\%hash);

Output:

$VAR1 = { 'a' => { 'b' => { 'c' => { 'd' => { '_val' => 'foo' } } } } };

The trick here is to keep a pointer ($p) to the insertion-point for the next category as you walk through the structure. You also need some way to distinguish values from categories - in this case I used a special "_val" key.

-sam