如何使用键列表获取深度哈希的元素?
How to get to an element of a deep hash using a list of keys?
给定哈希和键列表,我如何访问键指定的值?
换句话说:
my $h = {};
my @key = qw(hello to everyone);
我怎么去
$h->{hello}->{to}->{everyone}
一气呵成?
不是我的答案 - 归功于 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"
把它放在这里是因为它是 gem 并且方便大家使用谷歌搜索。
我希望原作者没问题(否则我会删除它)。
给定哈希和键列表,我如何访问键指定的值?
换句话说:
my $h = {};
my @key = qw(hello to everyone);
我怎么去
$h->{hello}->{to}->{everyone}
一气呵成?
不是我的答案 - 归功于 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"
把它放在这里是因为它是 gem 并且方便大家使用谷歌搜索。
我希望原作者没问题(否则我会删除它)。