On 03/14/2014 01:03 PM, Ralph Grove 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?
perl doesn't guarantee any evaluation order. when doing side effects
like this don't expect any particular result unless you control things
explicitly.
lists of args passed to subs and ops are evaluated left to right. that
can be useful if you really want to control evaluation order.
Thanks,
Ralph
sub doit {
return ++$g ;
}
$g = 0;
my $sum = $g + doit() + doit();
use List::Util qw( sum ) ;
my $sum = sum( $g, doit(), doit() ) ;
that will do what you think it should do.
since + officially doesn't care about left to right ordering, perl does
what it thinks will be efficient. it can't tell doit() is modifying $g.
but even better DON'T code that way!! even if order was specified that
is a very dangerous action at a distance piece of code.
uri
--
Uri Guttman - The Perl Hunter
The Best Perl Jobs, The Best Perl Hackers
http://PerlHunter.com
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/