给定代码:

my $x = 1;

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

我希望$x180:
$x = $x * 5 * ($x += 5); #$x = 1
$x = $x * 5 * 6;         #$x = 6
$x = 30 * 6;
$x = 180;
180;

而是30;但是,如果我更改条款的顺序:
$x = ($x += 5) * $x * 5;

我确实得到180。我感到困惑的原因是 perldoc perlop 很清楚地说:



由于($x += 5)在括号中,因此它应该是一个术语,因此无论表达式的顺序如何,都应首先执行。

最佳答案

提出问题的举动给了我答案:术语具有最高优先级。这意味着将对第一部分代码中的$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

关于perl - Perl如何决定对表达式中的项求值的顺序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1682332/

10-12 00:43