On Fri, Mar 14, 2014 at 6:03 PM, Ralph Grove <grov...@jmu.edu> wrote:
> I'm trying to determine how Perl evaluates operands for expressions. I > expected the following code to output 3, 4, and 5, as it would if executed > as a C++ or Java program. The actual output that I get (v5.16.2), however, > is 4, 4, and 5. This leads me to believe that operand evaluation is either > non-deterministic and compiler-dependent, or it's simply broken. > > The Perl documentation discusses operator evaluation, but doesn't directly > address operand evaluation order. Does anyone know of a good resource for > this information? > > Thanks, > Ralph > > > > sub doit { > return ++$g ; > } > > $g = 0; > my $sum = $g + doit() + doit(); > print "$sum \n"; > > $g = 0; > $sum = doit() + $g + doit(); > print "$sum \n"; > > $g = 0; > $sum = doit() + doit() + $g; > print "$sum \n"; http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement In particular: ---- Note that just as in C, Perl doesn't define *when* the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. ---- For what it's worth, here's some hackery to see the current order: use 5.010; sub TIESCALAR { my $class = shift; return bless {val => 0}, $class; } sub FETCH { my $self = shift; my $val = $self->{val}; warn "FETCH called, returning $val"; $val } sub STORE { warn "STORE called with $_[1]"; my $self = shift; $self->{val} = shift; } tie my $g, __PACKAGE__; sub doit { say " doit: will run ++\$g now:"; my $ret = ++$g; say " doit: \$g set to $ret, returning that"; return $ret; } say "First:"; $g = 0; say "^\$g = 0^"; my $sum = $g + doit() + doit(); print "$sum \n\n\n"; say "Second:"; $g = 0; say "^\$g = 0^"; $sum = doit() + $g + doit(); print "$sum \n\n\n"; say "Third:"; $g = 0; say "^\$g = 0^"; $sum = doit() + doit() + $g; print "$sum \n\n\n"; As to why THAT specific order, well, you're on the wrong mailing list :D Try perl5-porters if you're interested, or dig into pp_hot.c in the perl source.