Scalar vs list context

In both cases the assignment to $r is forcing scalar context on the do. However in the first case scalar context on a list returns the last value of the list, '44'.

In the second instance the assignment to my ($x) forces a list context, The result of assigning to a list in scalar context is the number of elements on the right hand side of the assignment. So you get.

map $_, 44 returns a list of length 1 containing (44)

my ($x) = assigns the results above in list context, because of the brackets around $x, to the list ($x) making $x = 44

The do block is in scalar context because of the assignment to $r, note the lack of brackets, and as I said above this returns the length of the right hand side of the list assignment. 1 in this case.

See what happens if you do this:

perl -wE 'say my $r = () = (1,3,5,7)'

First of all, neither do returns a list. They are evaluated in scalar context so they must return a single scalar, not an arbitrary number of scalars ("a list").

In the first case, the do returns the result of evaluating 44 in scalar context. This returns 44.

scalar(    44    ) ⇒ 44

In the second case, the do returns the result of evaluating a list assignment in scalar context. This returns the number of elements returned by the right-hand side of the assignment.

scalar(    () = 44    ) ⇒ 1

I believe the real cause of your confusion is that you don't know about the assignment operators and how they are affected by context. If so, see Scalar vs List Assignment Operator for the answer to your real question.

Tags:

Perl