in reply to Need explanatiin for subtle difference

Hello McA,

Assignment to a scalar variable puts the right-hand-side of the assignment into scalar context — which means the return statement is evaluated in scalar context.

Now, evaluating a list in scalar context invokes the Comma Operator, which “evaluates its left argument, throws that value away, then evaluates its right argument and returns that value.” And since the comma operator is left associative, the final (i.e., right-most) comma is evaluated last, so the last element of the list is returned.

Evaluating an array in scalar context returns the number of elements in the array:

If you evaluate an array in scalar context, it returns the length of the array. (Note that this is not true of lists, which return the last value, like the C comma operator, nor of built-in functions, which return whatever they feel like returning.)

perldata#Scalar-values.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Need explanation for subtle difference
by AnomalousMonk (Archbishop) on May 26, 2015 at 13:09 UTC
    ... evaluates its left argument, throws that value away, then evaluates its right argument and returns that value.

    McA: As e.g.:

    c:\@Work\Perl\monks>perl -wMstrict -le "sub foo { print 'hi from foo()'; } my $bar = 42; ;; my $agent = (foo(), $bar, 666, 99); print qq{agent $agent}; " Useless use of private variable in void context at -e line 1. Useless use of a constant (666) in void context at -e line 1. hi from foo() agent 99
    Note the  Useless use of ... warnings for the variable and constant as these are evaluated and thrown away. Perl understands that the evaluation of a subroutine may have (useful) side-effects.


    Give a man a fish:  <%-(-(-(-<