Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl print a value I don't expect after incrementing?

Tags:

perl

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"?

like image 885
planetp Avatar asked Aug 05 '11 21:08

planetp


2 Answers

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.

like image 147
ikegami Avatar answered Oct 04 '22 18:10

ikegami


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".

like image 45
Eugene Yarmash Avatar answered Oct 04 '22 17:10

Eugene Yarmash