为什么使用大括号初始化一些哈希,还有一些使用括号? [英] Why are some hashes initialized using curly braces, and some with parentheses?

查看:126
本文介绍了为什么使用大括号初始化一些哈希,还有一些使用括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  my%HoH =(
flintstones = > {
丈夫=>fred,
pal =>barney,
},
jetsons => {
husband => george,
wife =>jane,
他的男孩=>elroy,#需要的钥匙引号
},
simpsons => {
丈夫=>本垒打,
妻子=>marge,
kid =>bart,
},
);

为什么最上面的散列(起始行1)是用括号初始化的,而使用大括号初始化子哈希?



从Python背景来看,我必须说Perl很奇怪:)。



使用圆括号初始化一个散列(或数组)。哈希是一组字符串和一组标量值之间的映射。

 %foo =(key1, value1,key2,value2,...); #%表示散列
%foo =(key1 =>value1,key2 =>value2,...); #相同的东西

大括号用于定义哈希参考。所有引用都是标量值。

  $ foo = {key1 => value1,key2 => value2,...}; #$表示标量

哈希是不是标量值。由于hash 中的值必须是标量,因此不可能使用散列作为另一个散列的值。

 %bar =(key3 =>%foo); #并不意味着你认为它的意思是

但是我们可以使用散列引用作为另一个散列值,因为哈希引用是标量。

  $ foo = {key1 => value1,key2 => value2}; 
%bar =(key3 => $ foo);
%baz =(key4 => {key5 =>value5,key6 =>value6});

这就是为什么你会看到带有花括号的列表中的括号。


I'm looking at the following code demonstrating nested hashes:

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

Why is it that the upper-most hash (starting line 1) is initialized using parentheses, whereas the sub-hashes are initialized using curly braces?

Coming from a python background I must say Perl is quite odd :).

解决方案

Coming from a Perl background I find Perl quite odd, too.

Use parentheses to initialize a hash (or an array). A hash is a map between a set of strings and a set of scalar values.

%foo = ( "key1", "value1",  "key2", "value2", ... );   #  % means hash
%foo = ( key1 => "value1",  key2 => "value2", ... );   # same thing

Braces are used to define a hash reference. All references are scalar values.

$foo = { key1 => "value1", key2 => "value2", ... };    #  $ means scalar

Hashes are not scalar values. Since the values in a hash must be scalars, it is therefore not possible to use a hash as a value of another hash.

%bar = ( key3 => %foo );     # doesn't mean what you think it means

But we can use hash references as values of another hash, because hash references are scalars.

$foo = { key1 => "value1", key2 => "value2" };
%bar = ( key3 => $foo );
%baz = ( key4 => { key5 => "value5", key6 => "value6" } );

And that is why you see parentheses surrounding a list of lists with braces.

这篇关于为什么使用大括号初始化一些哈希,还有一些使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆