Search code examples
perlhashdereference

Perl %{$var} vs %$var


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";
    }
}

Solution

  • 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 :-)