Perl array vs list

前端 未结 6 1219
余生分开走
余生分开走 2020-11-28 05:01

I have two data structures in Perl:

An array:

my @array2 = ( \"1\", \"2\", \"3\");

for $elem (@array2) {
    print $elem.\"\\n\";
}
<
6条回答
  •  星月不相逢
    2020-11-28 06:01

    The square brackets are used to create an anonymous array. When evaluated, it returns a reference to this array, not the actual array values.

    Parentheses have no such hidden property, but simply override precedence inside expressions, much like in math. For example:

    my @array = 1,2,3;
    

    Is actually evaluated like this:

    my @array = 1;
    2,3; # causes the warning "Useless use of constant in void context"
    

    because the = operator has higher precedence than the commas. So to get around that, we use parentheses when assigning arrays, like so:

    my @array = (1,2,3);
    

    Your example:

    my @array = [1,2,3];
    

    is somewhat like saying this:

    my @tmp = (1,2,3);
    my @array = \@tmp;
    

    Where the \ is used to create a reference to the @tmp array.

提交回复
热议问题