List assignment to array affects scalar results

M

Mark

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
 
C

C.DeRykus

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

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)
and the additional elements in @ary are discarded.
@b is then assigned ($x,$y,$z) and then is evaluated
in scalar context to yield 3.
 
X

Xho Jingleheimerschmidt

Mark said:
Why does the introduction of the assignment to @b affect the value of
$cnt?

It is not the array that does it, it is the extra assignment.
use strict;
use warnings;

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


$cnt = ( ($x,$y,$z) = @ary );

The list assignment is evaluated in a scalar context.
print "cnt=$cnt\n"; # produces 5

my @b;
$cnt = ( @b = ($x,$y,$z) = @ary );

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 );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top