Inconsistent evaluation in the result list of an assignment statement in Perl?

The score in the results list looks inconsistent in scalar and contextual contexts. As shown below, the code snippet shows that the left side of the assignment (=) is evaluated in the context of a list, but the list on the right is evaluated in a scalar context. Is this and any linguistic principle expected to explain this behavior?

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

      

+3


source to share


2 answers


This does not contradict, as it does something completely different.

Every statement in perl has specific behavior in list and scalar context, and these are often different. In the case of assigning a list in the context of a list, it returns its left operand, whereas in a scalar context, it returns the number of elements in its right operand.



Note that this value does things like this work:

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

      

+5


source


It's just a matter of defining semantics this way.

Its from perldoc perlop



Likewise, assigning a list in the context of a list creates a list of lvalues ​​assigned, and assigning a list in a scalar context returns the number of elements created by the expression on the right side of the assignment.

+4


source







All Articles