在Perl中切片嵌套哈希

时间:2012-09-17 17:04:38

标签: perl hash slice

假设我有一个哈希,我可以索引为:

$hash{$document}{$word}

从我在线阅读的内容(虽然我在perlreftutperldscperllol上找不到此内容),如果我使用{{1},我可以使用列表切片哈希我的哈希上的前缀表示我希望哈希返回一个列表。但是,如果我尝试使用列表@切片我的哈希:

@list

我收到了几个@%hash{$document}{@list} 错误。

如何在Perl中删除嵌套哈希?

2 个答案:

答案 0 :(得分:7)

哈希的sigill必须是@,如下所示:

@{$hash{$document}}{@list}

假设@list包含%hash的有效密钥,它将返回相应的值,如果密钥不存在,则返回undef

这基于散列片的一般规则:

%foo = ( a => 1, b => 2, c => 3 );
print @foo{'a','b'};               # prints 12
%bar = ( foo => \%foo );           # foo is now a reference in %bar
print @{ $bar{foo} }{'a','b'};     # prints 12, same data as before

答案 1 :(得分:4)

首先,当您希望从哈希切片中获取列表时,请先使用@ sigil。 %在这里毫无意义。

其次,您应该了解$hash{$document}值不是哈希值或数组。它是一个引用 - 对数组的哈希OR。

说完这些,你可以使用这样的东西:

@{ $hash{$document} }{ @list };

...因此您取消引用$hash{$document}的值,然后在其上使用哈希切片。例如:

my %hash = (
    'one' => {
        'first'  => 1,
        'second' => 2,
     },
     'two' => {
        'third'  => 3,
        'fourth' => 4,
     } 
);

my $key  = 'one';
my @list = ('first', 'second');

print $_, "\n" for @{ $hash{$key} }{@list};
# ...gives 1\n2\n