On Thu, 15 Jul 2010, David Golden wrote: > On Thu, Jul 15, 2010 at 2:31 PM, Jan Dubois <jand@activestate.com> wrote: > > $ perl -E 'sub AUTOLOAD { say $AUTOLOAD; ++$i } say a() + b() * c()' > > main::a > > main::b > > main::c > > 7 > > > > So it does call a() first, even though the multiplication of b() and c() > > happens before the result is added to a(). But there is nothing in the > > operator precedence description that would forbid Perl from delaying > > evaluation of a() until after b() * c() has been computed. > > C<< a() >> is a term. Perlop says "A TERM has the highest precedence > in Perl." Doesn't that meant that all terms get evaluated first, then > all lower precedence operations happen. And because terms are left > associative, they should be evaluated left to right. Precedence and associativity are all about how the parser would insert parenthesis into an expression to disambiguate its meaning; it does not for example change the commutative property of addition: (a + b) has to be the same as (b + a), otherwise the operation is no longer an addition. And in a() * b() + c() Perl will indeed perform the multiplication before evaluating c(): --------------------------------------------------------------------------------- use 5.010; use overload "+" => sub { op("+", @_) }, "*" => sub { op("*", @_) }, fallback => 1; sub op { my ($op,$a,$b,$swap) = @_; ($a,$b) = ($b,$a) if $swap; $_ = ref $_ ? $_->{i} : $_ for $a, $b; my $res = eval "$a $op $b"; say "$a $op $b => $res"; return $res; } sub AUTOLOAD { say $AUTOLOAD; bless { i => ++$i } => __PACKAGE__ } sub DESTROY {} say a() * b() + c(); --------------------------------------------------------------------------------- main::a main::b 1 * 2 => 2 main::c 2 + 3 => 5 5 --------------------------------------------------------------------------------- Cheers, -JanThread Previous | Thread Next