Printing an array within double quotes

后端 未结 5 1739
栀梦
栀梦 2020-12-18 08:17
my @a = (1,2,3,4,5);

print @a;      #output: 12345

print \"\\n\";

print \"@a\";    #output: 1 2 3 4 5

Printing an array by putting its name with

5条回答
  •  醉话见心
    2020-12-18 08:40

    When Perl sees an array in an interpolated string, it rewrites it using join:

    print "@array";
    

    becomes

    print join($" => @array);
    

    by default, the value of $" is equal to a single space.

    You can configure this behavior by localizing a change to $"

    print "@array";     # '1 2 3 4 5'
    {
        local $" = '';  # "
        print "@array"; # '12345'
    }
    print "@array";     # '1 2 3 4 5' 
    

    You can see how Perl rewrites your interpolated strings using the -q option of the core B::Deparse module:

    $ perl -MO=Deparse,-q -e 'print "@array"'
    print join($", @array);
    -e syntax OK
    

提交回复
热议问题