Slicing a nested hash in Perl

扶醉桌前 提交于 2019-12-05 12:06:33

The sigill for your hash must be @, like so:

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

Assuming @list contains valid keys for %hash it will return the corresponding values, or undef if the key does not exist.

This is based on the general rule of a hash slice:

%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

First, when you expect to get a list from a hash slice, use @ sigil first. % is pointless here.

Second, you should understand that $hash{$document} value is not a hash or array. It's a reference - to a hash OR to an array.

With all this said, you might use something like this:

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

... so you dereference value of $hash{$document}, then use a hash slice over it. For example:

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!