# List assignment to array affects scalar results

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Why does the introduction of the assignment to @b affect the value of
\$cnt?

use strict;
use warnings;

my \$cnt;
my(\$x,\$y,\$z);
my(@ary) = qw(a b c d e);

\$cnt = ( (\$x,\$y,\$z) = @ary );
print "cnt=\$cnt\n"; # produces 5

my @b;
\$cnt = ( @b = (\$x,\$y,\$z) = @ary );
print "cnt=\$cnt\n"; # produces 3

## Re: List assignment to array affects scalar results

See:  perldoc perldata  and its explanations
of lists and list vs. scalar context

Specifically, from that doc:

List assignment in scalar context returns the
number of elements produced by the expression
on the right side of the assignment:

\$x =(\$foo,\$bar) = (3,2,1));# set \$x to 3, not 2
...

Similarly, in your first case, that evaluates to 5.
The eventual array assignment to @b in the second
case is also evaluated in scalar contest. The first
three elements in @ary are assigned to (\$x,\$x,\$z)
@b is then assigned (\$x,\$y,\$z) and then is evaluated
in scalar  context to yield 3.

--
Charles DeRykus

## Re: List assignment to array affects scalar results

Mark wrote:

It is not the array that does it, it is the extra assignment.

The list assignment is evaluated in a scalar context.

The initial list assignment is evaluated in a *list* context, not a
scalar context.  The magic only applies to list assignment in a scalar
context.

You get the same thing using a non-array:

\$cnt = ( (\$x1,\$x2,\$x3) = (\$x,\$y,\$z) = @ary );