%{$var}%$var有什么区别?我尝试了这段代码,但是有错误:


每个引用在test.pl第21行都是实验性的。
对每个引用的引用都必须在test.pl处为unhlessed hashref或arrayref
第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";
    }
}


但是这段代码可以正常工作:

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

最佳答案

使用%$HoH{$i}可以将$ HoH用作哈希引用,而使用%{$HoH{$i}}可以将$HoH{$i}用作哈希引用,这就是你想要的...而且,代码上的use strict :-)

10-07 22:58