Why does Perl print a value I don't expect after incrementing?
I'm running this one-liner from the command line:
perl -MList::Util=sum -E 'my $x = 0; say sum(++$x, ++$x)'
开发者_高级运维Why does it say "4"
instead of "3"
?
First, keep in mind that Perl passes by reference. That means
sum(++$x, ++$x)
is basically the same as
do {
local @_;
alias $_[0] = ++$x;
alias $_[1] = ++$x;
∑
}
Pre-increment returns the variable itself as opposed to a copy of it*, so that means both $_[0]
and $_[1]
are aliased to $x
. Therefore, sum
sees the current value of $x
(2
) for both arguments.
Rule of thumb: Don't modify and read a value in the same statement.
* — This isn't documented, but you're asking why Perl is behaving the way it does.
You are modifying $x
twice in the same statement. According to the docs, Perl will not guarantee what the result of this statements is. So it may quite be "2"
or "0"
.
Because both incrementers are executed before the sum is calculated.
After both execute, x = 2
.
2 + 2 = 4.
精彩评论