How to get a hash fragment from a hash hash?

I have a hash like:

my %h = ( a => { one => 1, two => 2 }, b => { three => 3, four => 4 }, c => { five => 5, six => 6 } ); print join(',', @{$h{a}{qw/one two/}}); 

The error I get: You cannot use the undefined value as an ARRAY link in q.pl 17 which is a line with printing.

I expected 1.2

+4
source share
2 answers

To get a hash fragment from a nested hash, you must stop linking to it in stages. You get the first level that you need:

 $h{'a'} 

You should now dereference this as a hash. However, since this is not a simple scalar, you must put it in braces. To get the entire hash, you must put % before the brackets:

 %{ $h{'a'} } 

Now you need a fragment, so you replace % with @ , since you get a few elements, and you also put the keys at the end as usual:

 @{ $h{'a'} }{ @keys } 

It might seem that it's easier to see braces separately:

 @{ }{ } $h{'a'} @keys 

To simplify this, v5.20 introduced postfix dereferencing . Instead of wrapping things in braces and working from the inside out, you can work from left to right:

 $h{a}->@{qw/one two/}; 

This @ the same as what you saw before the first bracket. You still know that this is a hash piece because the bracket follows the character.

+20
source

to try

 print join(',',@{$h{'a'}}{qw/one two/}); 

Using Data :: Dumper helps a lot in such cases.

+2
source

All Articles