Perl%{$ var} vs%$ var

ste*_*ytw 3 perl hash dereference

%{$var}和之间有什么区别%$var?我试过这段代码,但是有错误:

每个引用都是test.pl第21行的实验.每个引用的参数类型必须是test.pl第21行的非反射hashref或arrayref.

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码运行正常:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*coS 7

随着%$HoH{$i}你做$斛散列引用,而与%{$HoH{$i}}你做的散列引用$HoH{$i},这是你想要的......而且,use strict您的代码:-)

  • @bounces,即使在测试中你必须使用它!在源代码中使用strict时的错误是完全不同的:"全局符号"$ HoH"需要显式的包名称`,这会给你答案. (2认同)