How does Perl decide which order to evaluate terms in an expression?

Based on the code:

my $x = 1;

$x = $x * 5 * ($x += 5);

I would expect $x 180:

$x = $x * 5 * ($x += 5); #$x = 1
$x = $x * 5 * 6;         #$x = 6
$x = 30 * 6;
$x = 180;
180;

But instead it is 30; however, if I reorder the members:

$x = ($x += 5) * $x * 5;

I get it 180. The reason I got confused is because it perldoc perlopsays very simply:

A TERM has the highest priority in Perl. These include variables, quotation and quotation operators, any expression in parentheses , and any function whose arguments are enclosed in parentheses.

Since it ($x += 5)is in parentheses, it must be a term and, therefore, executed first, regardless of the order of expression.

+5
source share
4

: . , $x 1, 5 5, ($x += 5) 6 ( $x 6):

$x = $x * 5 * ($x += 5);
address of $x = $x * 5 * ($x += 5); #evaluate $x as an lvalue
address of $x = 1 * 5 * ($x += 5);  #evaluate $x as an rvalue
address of $x = 1 * 5 * ($x += 5);  #evaluate 5
address of $x = 1 * 5 * 6;          #evaluate ($x += 5), $x is now 6
address of $x = 1 * 5 * 6;          #evaluate 1 * 5
address of $x = 5 * 6;              #evaluate 1 * 5
address of $x = 30;                 #evaluate 5 * 6
30;                                 #evaluate address of $x = 30

, :

$x = ($x += 5) * $x * 5; 
address of $x = ($x += 5) * $x * 5; #evaluate $x as an lvalue
address of $x = 6 * $x * 5;         #evaluate ($x += 5), $x is now 6
address of $x = 6 * 6 * 5;          #evaluate $x as an rvalue
address of $x = 6 * 6 * 5;          #evaluate 5
address of $x = 36 * 5;             #evaluate 6 * 6
address of $x = 180;                #evaluate 36 * 5
180;                                #evaluate $x = 180
+16

, , perldoc perlop, , , , B:: Deparse:

perl -MO=Deparse,-p,-q,-sC
my $x = 1;
$x = $x * 5 * ($x += 5);

^D

:

(my $x = 1);
($x = (($x * 5) * ($x += 5)));
- syntax OK

, , :

($x = (($x * 5) * ($x += 5)));
($x = ((1 * 5) * ($x += 5)));
($x = ((5) * (6))); # and side-effect: $x is now 6
($x = (5 * 6));
($x = (30));
($x = 30);
$x = 30;

, , $x 6, -, (1) , 30.

+9

$x TERM. ( ), .

+4

* , . , **, ($x += 5) .

+2

All Articles