【问题标题】:How to get to an element of a deep hash using a list of keys? [duplicate]如何使用键列表获取深度散列的元素? [复制]
【发布时间】:2021-04-05 02:55:58
【问题描述】:

给定一个散列和一个键列表,我如何访问键指定的值?

换句话说:

my $h = {};

my @key = qw(hello to everyone);

我怎么去

$h->{hello}->{to}->{everyone}

一口气?

【问题讨论】:

标签: perl


【解决方案1】:

不是我的答案 - 通过Polettix 归功于Merlyn on PerlMonks。

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"

把它放在这里是因为它是一个瑰宝,并且便于每个人在谷歌上搜索。

我希望原作者没问题(如果不是,我会删除它)。

【讨论】:

  • 这与this基本相同,只是链接版本没有reduce的开销。
  • 最好写成:return reduce { \($$a->{$b}) } \shift, @_;
  • @ikegami - 两者都完成
猜你喜欢
  • 2015-05-31
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2013-07-08
  • 2013-01-13
  • 2013-04-14
  • 2021-11-03
  • 1970-01-01
相关资源
最近更新 更多