Slicing a nested hash in Perl

Let's say I have a hash that I can index as:

$hash{$document}{$word} 

From what I read online (although I couldn't find it on perlreftut , perldsc or perllol ), I can cut the hash using a list if I use @ prefix on my hash to indicate that I want the hash to return a list . However, if I try to cut my hash using the @list :

 @%hash{$document}{@list} 

I get a few "Scalar values ... better written" errors.

How can I hide nested hashes in Perl?

+4
source share
2 answers

The sigil for your hash should be @ , for example:

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

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

This is based on the general hash rule:

 %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 
+6
source

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

Secondly, you should understand that the value of $hash{$document} not a hash or an array. This is a reference to a hash OR to an array.

With all of this in mind, you can use something like this:

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

... so you are looking for the value of $hash{$document} , and then use the hash fragment above it. For instance:

 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 
+4
source

Source: https://habr.com/ru/post/1434661/


All Articles