请问这两种哈希初始化方法有什么区别?
第一种方法:
$items{"food"} = "4.4";
$items{"water"} = "5.0";
$items{"shelter"} = "1.1";
foreach $item (keys $items) {
print "$item\n";
}
输出为:
food
water
shelter
第二种方法:
%items = {
'food' => '4.4',
'water' => '5.0',
'shelter' => '1.1'
};
foreach $item (keys %items) {
print "$item\n";
}
输出是哈希引用:
HASH(0x8cc41bc)
为什么第二种方法返回引用而不是实际值?
答案 0 :(得分:8)
因为你误解了{}
的作用。
它创建一个匿名哈希,返回一个引用。
您刚刚完成的功能类似于:
my %stuff = (
'food' => '4.4',
'water' => '5.0',
'shelter' => '1.1'
);
my %items = \%stuff;
这没有多大意义。
使用()
初始化哈希,它可以正常工作。
答案 1 :(得分:2)
这是一个很好的示例,说明为什么始终打开Perl代码中的警告。
$ perl -Mwarnings -E'%h = {}; say keys %h'
Reference found where even-sized list expected at -e line 1.
HASH(0xbb6d48)
有关更详细的说明,请同时使用“诊断”。
$ perl -Mwarnings -Mdiagnostics -E'%h = {}; say keys %h'
Reference found where even-sized list expected at -e line 1 (#1)
(W misc) You gave a single reference where Perl was expecting a list
with an even number of elements (for assignment to a hash). This usually
means that you used the anon hash constructor when you meant to use
parens. In any case, a hash requires key/value pairs.
%hash = { one => 1, two => 2, }; # WRONG
%hash = [ qw/ an anon array / ]; # WRONG
%hash = ( one => 1, two => 2, ); # right
%hash = qw( one 1 two 2 ); # also fine
HASH(0x253ad48)