Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

= and , operators in Perl

Tags:

perl

Please explain this apparently inconsistent behaviour:

$a = b, c;
print $a; # this prints: b

$a = (b, c);
print $a; # this prints: c
like image 461
Literat Avatar asked Nov 28 '22 09:11

Literat


1 Answers

The = operator has higher precedence than ,. And the comma operator throws away its left argument and returns the right one.

Note that the comma operator behaves differently depending on context. From perldoc perlop:

Binary "," is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator.

In list context, it's just the list argument separator, and inserts both its arguments into the list. These arguments are also evaluated from left to right.

like image 79
Eugene Yarmash Avatar answered Dec 27 '22 05:12

Eugene Yarmash