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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Building an arbitrary-depth, multi-level hash
by ikegami (Patriarch) on Feb 28, 2009 at 22:15 UTC | |
by samtregar (Abbot) on Feb 28, 2009 at 22:19 UTC | |
by ikegami (Patriarch) on Feb 28, 2009 at 22:33 UTC | |
Re^2: Building an arbitrary-depth, multi-level hash
by Anonymous Monk on Feb 28, 2009 at 22:57 UTC | |
Re^2: Building an arbitrary-depth, multi-level hash
by repellent (Priest) on Mar 01, 2009 at 21:13 UTC | |
by ikegami (Patriarch) on Mar 01, 2009 at 21:26 UTC | |
by repellent (Priest) on Mar 01, 2009 at 22:47 UTC | |
by ikegami (Patriarch) on Mar 02, 2009 at 02:50 UTC | |
Re^2: Building an arbitrary-depth, multi-level hash
by zentara (Archbishop) on Mar 01, 2009 at 15:30 UTC |
In Section
Seekers of Perl Wisdom