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
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.
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.
Scalar variables contain only one value at a time, and array variables contain a list of values.
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.
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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With