20

我正在查看以下演示嵌套哈希的代码:

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 很奇怪:)。

4

3 回答 3

30

来自 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" } );

这就是为什么您会看到括号围绕带有大括号的列表列表。

于 2012-08-07T05:39:50.457 回答
9

本质区别 (....) 用于创建哈希。{....} 用于创建哈希引用

my %hash  = ( a => 1 , b => 2 ) ;
my $hash_ref  = { a => 1 , b => 2 } ;

更详细一点 - {....} 进行匿名哈希并返回对它的引用,该引用分配给标量$hash_ref

编辑以提供更多细节

于 2012-08-07T07:54:49.210 回答
6

首先,括号除了在这里改变优先级之外什么都不做。它们与列表创建、哈希创建或哈希初始化无关。

例如,以下两行是 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,
);
于 2012-08-07T06:00:36.540 回答