in reply to Re^3: Building an arbitrary-depth, multi-level hash
in thread Building an arbitrary-depth, multi-level hash

Sorry, I was too brief. What I meant was in the absence of assigning value to the key _val: (note the change with comments)
use strict; use warnings; use Data::Dumper qw( Dumper ); sub samtregar { my $p = shift; my $val = pop; for my $item (@_) { $p->{$item} ||= {}; $p = $p->{$item}; } ### $p->{_val} = $val; } sub repellent { my $p = \shift; my $val = pop; $p = \$$p->{$_} for @_; ### $$p->{_val} = $val; } { samtregar(my $samtregar={}, qw( a b c d ), 'foo'); repellent(my $repellent, qw( a b c d ), 'foo'); { local $Data::Dumper::Useqq = 1; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; print("samtregar: ", Dumper($samtregar), "\n"); print("repellent: ", Dumper($repellent), "\n"); } } __END__ samtregar: {"a" => {"b" => {"c" => {"d" => {}}}}} repellent: {"a" => {"b" => {"c" => {"d" => undef}}}}

while the nested hashes are being built, it doesn't leave an empty {} around. This behavior could be desirable.

I didn't mean to say that mine doesn't vivify. It's almost the same, just subtly different as shown above.

Hmmm ... as for the fetchers, shouldn't it be more consistent with:
use strict; use warnings; use Data::Dumper qw( Dumper ); sub samtregar_fetcher { my $p = shift; for my $item (@_) { ### last if !$p->{$item}; $p->{$item} ||= {}; $p = $p->{$item}; } return $p->{_val} } sub repellent_fetcher { my $p = \shift; ### my $val = pop; $p = \$$p->{$_} for @_; return $$p->{_val}; } { samtregar_fetcher(my $samtregar={}, qw( a b c d )); repellent_fetcher(my $repellent, qw( a b c d )); { local $Data::Dumper::Useqq = 1; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; print("samtregar: ", Dumper($samtregar), "\n"); print("repellent: ", Dumper($repellent), "\n"); } } __END__ samtregar: {"a" => {"b" => {"c" => {"d" => {}}}}} repellent: {"a" => {"b" => {"c" => {"d" => {}}}}}

Replies are listed 'Best First'.
Re^5: Building an arbitrary-depth, multi-level hash
by ikegami (Patriarch) on Mar 02, 2009 at 02:50 UTC
    I disagree. Why would fetching add to the data structure.