develooper Front page | perl.perl5.porters | Postings from July 2010

RE: Order of evaluation of terms (was peephole optimiser could prune more dead code)

Thread Previous | Thread Next
From:
Jan Dubois
Date:
July 15, 2010 12:39
Subject:
RE: Order of evaluation of terms (was peephole optimiser could prune more dead code)
Message ID:
020801cb2455$61e99830$25bcc890$@activestate.com
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,
-Jan




Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About