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

Re: Order of evaluation of terms (was peephole optimiser couldprune more dead code)

Thread Previous | Thread Next
July 15, 2010 12:42
Re: Order of evaluation of terms (was peephole optimiser couldprune more dead code)
Message ID:
David Golden wrote:
>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.

No.  It only means that adding surrounding operators can't change how a
term parses.  E.g., putting "5*" in front of "a()" doesn't change "a()"
being parsed as a complete function call expression.  This is unlike an
expression such as "1+2", which on its own parses as a complete addition,
but with "5*" in front it ceases to be a complete subexpression (the
"1", but not the "+2", becomes part of a multiplication).

>                                         And because terms are left

It's meaningless to speak of the associativity of a term (atomic
expression).  The concept of associativity only applies to infix
operators.  There is in fact a doc bug here, in that perlop ascribes
associativity to terms and to "list operators (leftward)" (a list operator
expression viewed from the left, from where it looks like a term).

>             they should be evaluated left to right.

No, that's not what associativity does.  Consider the / operator,
which is left associative.  The left associativity means that the
expression "20 / 2 / 2" groups as "(20 / 2) / 2", rather than "20 /
(2 / 2)" (which is what would happen if it were right associative).
This means that the left division operation (20 / 2) must be performed
before the right division operation (10 / 2).  But in "20 / 2 + 9 / 3",
the associativity doesn't come into play, and it's perfectly valid for
the right division (9 / 3) to happen before the left division (20 / 2).

Associativity is, as someone else said, a tiebreaker for precedence.
It's what you use to determine the grouping when the competing operators
have equal precedence.

Precedence and associativity imply certain things about order of
evaluation, but the implications are minimal.  In general, if a language
does not have other specific guarantees about order of evaluation, any
order is acceptable for the evaluation of the atomic terms and for the
operations represented by the operators.  The order is constrained only
by the inherent need for the operands of any single operation to have
each been fully evaluated before that operation can take place.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About