Perl 增量运算符 [英] Perl increment operator

查看:74
本文介绍了Perl 增量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$a = 10; 
$b = (++$a) + (++$a) + (++$a);
print $b;

我得到了答案 37.谁能解释一下这个操作是如何进行的以及结果是如何得到 37 的.

I am getting the answer 37. Can anybody explain how this operation is proceeding and how the result is getting 37.

按照我的逻辑,它应该是 36:

As per my logic it should be 36:

(++$a) + (++$a) + (++$a)
   11  +    12  +    13  = 36

但我得到了答案 37

推荐答案

Perl 的执行方式为

Perl's is executing this as

( ( $a = $a + 1 ) + ( $a = $a + 1 ) ) + ( $a = $a + 1 )

您甚至将 ++$a 放在括号中,以便说明它们应该在添加之前首先发生,尽管它们的优先级更高

You have even put the ++$a in parentheses so to say that they should happen first, before the additions, although they are of higher priority anyway

这以赋值运算符=返回其第一个操作数这一事实为中心,它允许像

This is centred around the fact that the assignment operator = returns its first operand, which allows operations like

(my $x = $y) =~ tr/A-Z/a-z/

如果赋值的结果只是从 $y 复制到 $xvalue 那么 tr// 会导致 Can't modify an constant item 或等效项,并且不会影响存储在任一变量中的内容

If the result of the assignment were simply the value copied from $y to $x then the tr/// would cause a Can't modify a constant item or the equivalent, and it would have no effect on what was stored in either variable

这里是变量$a,执行如下

  • 执行第一个增量,返回$a
    $a 现在是 11

执行第二次增量,再次返回$a
$a 现在是 12

Execute the second increment, returning $a again
$a is now 12

执行第一次加法,将两次增量返回的相加——都是 $a
$a 是 12,所以 $a + $a 是 24

Execute the first addition, which adds what was returned by the two increments—both $a
$a is 12, so $a + $a is 24

执行第三次增量,再次返回$a
$a 现在是 13

Execute the third increment, returning $a again
$a is now 13

执行第二次加法,将第一次加法返回的值 (24) 和第三次加法 ($a) 相加
$a 是 13,所以 24 + $a 是 37

Execute the second addition, which adds the what was returned by the first addition (24) and the third increment ($a)
$a is 13, so 24 + $a is 37

请注意,不应依赖于此.除了说我们未定义之外,它没有在任何地方记录,并且行为可能会随着 Perl 的任何版本而改变

Note that this should not be relied on. It is not documented anywhere except to say that it us undefined, and the behaviour could change with any release of Perl

这篇关于Perl 增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆