Why are some hashes initialized using curly braces, and some with parentheses?

前端 未结 3 396
予麋鹿
予麋鹿 2021-02-05 08:42

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

my %HoH = (
    flintstones => {
        husband   => \"fred\",
        pal       => \"b         


        
3条回答
  •  名媛妹妹
    2021-02-05 09:24

    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.

提交回复
热议问题