我正在查看以下代码,演示嵌套哈希:
my %HoH = (
flintstones => {
husband => "fred",
pal => "barney",
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy", # Key quotes needed.
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);
为什么使用括号初始化最上面的哈希(起始行1),而使用花括号初始化子哈希?
来自python背景我必须说Perl很奇怪:)。
答案 0 :(得分:26)
来自Perl背景我发现Perl也很奇怪。
使用括号初始化散列(或数组)。哈希是一组字符串和一组标量值之间的映射。
%foo = ( "key1", "value1", "key2", "value2", ... ); # % means hash
%foo = ( key1 => "value1", key2 => "value2", ... ); # same thing
大括号用于定义哈希引用。所有引用都是标量值。
$foo = { key1 => "value1", key2 => "value2", ... }; # $ means scalar
哈希不是标量值。由于散列中的值必须是标量,因此无法将散列用作另一个散列的值。
%bar = ( key3 => %foo ); # doesn't mean what you think it means
但是我们可以使用散列引用作为另一个散列的值,因为散列引用是标量。
$foo = { key1 => "value1", key2 => "value2" };
%bar = ( key3 => $foo );
%baz = ( key4 => { key5 => "value5", key6 => "value6" } );
这就是为什么你看到围绕带括号的列表列表的括号。
答案 1 :(得分:7)
本质区别(....)用于创建哈希。 {....}用于创建哈希引用
my %hash = ( a => 1 , b => 2 ) ;
my $hash_ref = { a => 1 , b => 2 } ;
更详细一点 - {....}创建一个匿名哈希并返回对它的引用,它与标量$hash_ref
以提供更多详细信息
答案 2 :(得分:6)
首先,parens除了改变优先权外什么都不做。它们从不与列表创建,哈希创建或哈希初始化无关。
例如,以下两行是100%等效的:
{ a => 1, b => 2 }
{ ( a => 1, b => 2 ) }
例如,以下两行是100%等效的:
sub f { return ( a => 1, b => 2 ) } my %hash = f();
sub f { return a => 1, b => 2 } my %hash = f();
其次,我们不会使用{ }
来初始化哈希值;一个人使用它创建一个哈希。 { }
等同于my %hash;
,但散列是匿名的。换句话说,
{ LIST }
与
基本相同do { my %anon = LIST; \%anon }
(但不会创建词汇范围)。
匿名哈希允许一个人写
my %HoH = (
flintstones => {
husband => "fred",
pal => "barney",
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy",
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);
而不是
my %flintstones = (
husband => "fred",
pal => "barney",
);
my %jetsons = (
husband => "george",
wife => "jane",
"his boy" => "elroy",
);
my %simpsons = (
husband => "homer",
wife => "marge",
kid => "bart",
);
my %HoH = (
flintstones => \%flinstones,
jetsons => \%jetsons,
simpsons => \%simpsons,
);