Perl %{$var} 与 %$var
Perl %{$var} vs %$var
%{$var}
和 %$var
有什么区别?我试过这段代码但有错误:
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";
}
}
但是这段代码工作正常:
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
在你的代码上:-)
这是因为解析散列与下标散列的优先级不同。它适用于第二个版本 - %{ $HoH{$i} }
- 因为你明确指出查找 $HoH{$i}
返回的值本身就是一个 hashref。
而 %$HoH{$i}
被解释为 %{ $HoH }{$i}
- 即。下标发生在表达式 $HoH
被解释为哈希引用之后 - 但事实并非如此。 %HoH
是一个散列,但未使用 $HoH
- 即它未定义。
%{$var}
和 %$var
有什么区别?我试过这段代码但有错误:
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";
}
}
但是这段代码工作正常:
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
在你的代码上:-)
这是因为解析散列与下标散列的优先级不同。它适用于第二个版本 - %{ $HoH{$i} }
- 因为你明确指出查找 $HoH{$i}
返回的值本身就是一个 hashref。
而 %$HoH{$i}
被解释为 %{ $HoH }{$i}
- 即。下标发生在表达式 $HoH
被解释为哈希引用之后 - 但事实并非如此。 %HoH
是一个散列,但未使用 $HoH
- 即它未定义。