为什么有些哈希使用大括号初始化,有的用括号?(Why are some hashes initial

2019-07-30 19:37发布

我在看下面的代码演示嵌套哈希:

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行),使用括号被初始化,而子散列用大括号初始化?

从蟒蛇背景的我必须说,Perl是一种很奇怪的:)。

Answer 1:

从一个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" } );

这就是为什么你看到周围列表用大括号列表括号。



Answer 2:

本质的区别(....)用于创建一个哈希值。 {....}被用于创建哈希参考

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

在一些详细信息- {....}使得一个匿名的哈希并将其至极的asigned标量返回引用$hash_ref

编辑,以得到更详细一点



Answer 3:

首先,括号做什么,但变化的优先位置。 他们从来没有无关列表的创建,创建哈希或哈希初始化。

例如,下面的两行是等价的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,
);


文章来源: Why are some hashes initialized using curly braces, and some with parentheses?
标签: perl hash