Ways to Flatten A Perl Array in Scalar Context Ways to Flatten A Perl Array in Scalar Context arrays arrays

Ways to Flatten A Perl Array in Scalar Context


The join function is commonly used to "flatten" lists. Lets you specify what you want between each element in the resulting string.

$scal = join(",", @arr);# $scal is no "1,2,3"


In your example, you're interpolating an array in a double-quoted string. What happens in those circumstances is is controlled by Perl's $" variable. From perldoc perlvar:

$LIST_SEPARATOR

$"

When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value. Default is a space. For example, this:

print "The array is: @array\n";

is equivalent to this:

print "The array is: " . join($", @array) . "\n";

Mnemonic: works in double-quoted context.

The default value for $" is a space. You can obviously change the value of $".

{  local $" = ':',  my @arr = (1, 2, 3);  my $scalar = "@arr"; # $scalar contains '1:2:3'}

As with any of Perl's special variables, it's always best to localise any changes within a code block.


You could also use join without any seperator

my $scalar = join( '' , @array ) ;

There is more than one way to do it.