Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalar vs list context

Tags:

perl

Wonder what is the rationale behind following two examples giving different results when in both cases do {} returns lists.

perl -wE 'say my $r = do {  (44); }'
44

perl -wE 'say my $r = do {  my ($x) = map $_, 44; }'
1
like image 437
mpapec Avatar asked Jan 14 '19 11:01

mpapec


People also ask

What is a scalar context?

In a list context, Perl gives the list of elements. But in a scalar context, it returns the number of elements in the array. When an operator functions on Scalars then its termed as Scalar Context. Note: Whenever you assign anything to a Scalar variable it will always give Scalar Context.

What is the use of scalar 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.

Can a scalar variable hold a list of values?

Scalar variables contain only one value at a time, and array variables contain a list of values.

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.


1 Answers

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)'
like image 125
JGNI Avatar answered Nov 09 '22 04:11

JGNI