Given a hash, and a list of keys how do I get access to the value specified by the keys?
In other words given:
my $h = {};
my @key = qw(hello to everyone);
how do I get to
$h->{hello}->{to}->{everyone}
in one go?
Given a hash, and a list of keys how do I get access to the value specified by the keys?
In other words given:
my $h = {};
my @key = qw(hello to everyone);
how do I get to
$h->{hello}->{to}->{everyone}
in one go?
Not my answer - credit goes to Merlyn on PerlMonks via Polettix.
use List::Util;
sub pointer_to_element {
return reduce(sub { \($$a->{$b}) }, \shift, @_);
}
my $h = { hello => {to => 'everyone'} };
my @key = qw/hello to/;
# get the element
my $scalar_ref = pointer_to_element($h, @key);
print $$scalar_ref, "\n"; # prints "everyone"
# set the element
$$scalar_ref = 'everybody';
# and check it
print "$hash{hello}{to}\n"; # prints "everybody"
Putting it here because it's a gem and for ease of Googling for everyone.
I hope it's ok with the original authors (and if not I'll delete this).