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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With