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

前端 未结 3 391
予麋鹿
予麋鹿 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

    First, the parens do nothing but change precedence here. They never have nothing to do with list creation, hash creation or hash initialisation.

    For example, the following two lines are 100% equivalent:

    {   a => 1, b => 2   }
    { ( a => 1, b => 2 ) }
    

    For example, the following two lines are 100% equivalent:

    sub f { return ( a => 1, b => 2 ) }    my %hash = f(); 
    sub f { return   a => 1, b => 2   }    my %hash = f(); 
    

    Second, one doesn't initialise a hash using { }; one creates a hash using it. { } is equivalent to my %hash;, except that the hash is anonymous. In other words,

    { LIST }
    

    is basically the same as

    do { my %anon = LIST; \%anon }
    

    (but doesn't create a lexical scope).

    Anonymous hashes allows one to write

    my %HoH = (
        flintstones => {
            husband   => "fred",
            pal       => "barney",
        },
        jetsons => {
            husband   => "george",
            wife      => "jane",
            "his boy" => "elroy",
        },
        simpsons => {
            husband   => "homer",
            wife      => "marge",
            kid       => "bart",
        },
    );
    

    instead of

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

提交回复
热议问题