Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to Flatten A Perl Array in Scalar Context

Tags:

I recently started learning perl and have a question that I'm not finding a clear answer to on the Internet. say I have something like this,

@arr = (1, 2, 3); $scal = "@arr" # $scal is now 123. 

Is the use of quotes the only way to flatten the array so that each element is stored in the scalar value? It seems improbable but I haven't found any other ways of doing this. Thanks in advance.

like image 387
Daniel Gratzer Avatar asked Apr 20 '12 10:04

Daniel Gratzer


People also ask

How do I assign an array to a scalar in Perl?

In order to provoke Scalar Context using an array, it is required to assign an array to a Scalar variable. When the condition section of the if-statement presumes a single value then that is Scalar Context. In the below program, if-statement contains array, in scalar context, array returns the number of elements in it.

What is scalar array in Perl?

An array is an ordered and mutable list of scalars. In Perl, scalars are defined as a single unit of data such as an integer, a floating-point, a character, a string, and so on. They are preceded by a $ when defined.

What is scalar function in Perl?

scalar keyword in Perl is used to convert the expression to scalar context. This is a forceful evaluation of expression to scalar context even if it works well in list context. Syntax: scalar expr.

What is dynamic array in Perl?

Perl arrays are dynamic in length, which means that elements can be added to and removed from the array as required. Perl provides four functions for this: shift, unshift, push and pop. shift removes and returns the first element from the array, reducing the array length by 1.


2 Answers

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" 
like image 194
Mat Avatar answered Oct 20 '22 00:10

Mat


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.

like image 35
Dave Cross Avatar answered Oct 20 '22 01:10

Dave Cross