Search code examples
perlactiveperl

Inconsistent evaluation on the result list of assignment operator in Perl?


The evaluation on the result list looks to be inconsistent in scalar and list context. As below code snippet shows, the left side of assignment operation (=) is evaluated in list context, but the list in the right side is evaluated when in scalar context. Is this expected and any language principle to explain this behavior?

print (($k, $v) = (3, 4, 5)); # output is 34
print scalar (($k, $v) = (3, 4, 5)); # output is 3

Solution

  • It isn't inconsistent so much as doing something completely different.

    Every operator in perl has a defined behaviour in list and scalar context, and they often are quite different. In the case of a list assignment, in list context, it returns its left operand, while in scalar context it returns a count of elements in its right operand.

    Note that this meaning makes things like this work:

    while ( my ($k,$v) = each %hash ) {