6

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

$hash{$document}{$word}

根据我在网上阅读的内容(尽管我在perlreftutperldscperllol上找不到此内容),如果我使用@哈希上的前缀表示我希望哈希返回一个列表,我可以使用列表对哈希进行切片。但是,如果我尝试使用 list 对哈希进行切片@list

@%hash{$document}{@list}

我收到几个"Scalar values ... better written" 错误。

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

4

2 回答 2

8

您的散列符号必须是@,如下所示:

@{$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
于 2012-09-17T17:09:45.213 回答
4

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

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

说了这么多,你可能会使用这样的东西:

@{ $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
于 2012-09-17T17:12:53.040 回答