Perl array vs list

前端 未结 6 1218
余生分开走
余生分开走 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 05:59

    The square brackets create an anonymous array, populate the array with the contents of the brackets, and return a reference to that array. In other words,

    [ "1", "2", "3" ]
    

    is basically the same as

    do { my @anon = ("1", "2", "3"); \@anon }
    

    So the code should look like

    my $array_ref = [ "1", "2", "3" ];
    
    for (@$array_ref) {  # Short for @{ $array_ref }
        print "$_\n";
    }
    

    or

    my @array_of_refs = ([ "1", "2", "3" ]);
    
    for my $array_ref (@array_of_refs) {
        for (@$array_ref) {
            print "$_\n";
        }
    }
    

提交回复
热议问题