Why does Perl print a value that I don't expect after an increase?

I run this single line key from the command line:

perl -MList::Util=sum -E 'my $x = 0; say sum(++$x, ++$x)'

Why is he talking "4"instead "3"?

+5
source share
3 answers

You change $xtwice in one expression. According to docs , Perl does not guarantee what the result of these statements is. Therefore, it may be "2"or "0".

+4
source

First, keep in mind that Perl follows a link. It means

sum(++$x, ++$x)

basically coincides with

do {
   local @_;
   alias $_[0] = ++$x;
   alias $_[1] = ++$x;
   ∑
}

Pre-increment , *, , $_[0] $_[1] $x. , sum $x (2) .

: .

* — This isn't documented, but you're asking why Perl is behaving the way it does.

+7

Since both increments are performed before calculating the sum.

After execution, execute x = 2.

2 + 2 = 4.
+3
source

All Articles