Reputation: 958
What's the difference between %{$var}
and %$var
? I tried this code but there's error:
each on reference is experimental at test.pl line 21. Type of argument to each on reference must be unblessed hashref or arrayref at test.pl line 21.
use feature 'say';
%HoH = (
1 => {
husband => "fred",
pal => "barney",
},
2 => {
husband => "george",
wife => "jane",
"his boy" => "elroy",
},
3 => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);
for ($i = 1; $i <= 3; $i++) {
while ( ($family, $roles) = each %$HoH{$i} ) {
say "$family: $roles";
}
}
But this code works fine:
use feature 'say';
%HoH = (
1 => {
husband => "fred",
pal => "barney",
},
2 => {
husband => "george",
wife => "jane",
"his boy" => "elroy",
},
3 => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);
for ($i = 1; $i <= 3; $i++) {
while ( ($family, $roles) = each %{$HoH{$i}} ) {
say "$family: $roles";
}
}
Upvotes: 3
Views: 1331
Reputation: 2808
Its due to the different precedence levels of resolving the hash vs subscripting the hash. It works with the second version - %{ $HoH{$i} }
- because you are unambiguously stating that the value returned by the lookup of $HoH{$i}
is itself, a hashref.
Whereas %$HoH{$i}
is interpreted as %{ $HoH }{$i}
- ie. the subscripting is happening after the expression $HoH
is interpreted as a hashref - which it isn't. %HoH
is a hash but $HoH
is not used - i.e. it's undefined.
Upvotes: 2
Reputation: 17721
With %$HoH{$i}
you make a hash reference of $HoH, while with %{$HoH{$i}}
you make a hash reference of $HoH{$i}
, which is what you want... And, use strict
on your code :-)
Upvotes: 7