in reply to Left-associative binary operators in Parse::RecDescent

What you want is grammar stratification to give you precedence levels (as opposed to relying on rule matching order as you do now). Put the lowest precedence stuff at the top/outermost level of the grammar, and the highest-precendence stuff at the bottom/innermost level. This is one standard technique for writing grammars.

The basic structure of stratified rules is like this (at least for binary operations):

## for right-associative ops: lower_prec_expr : higher_prec_expr lower_prec_op lower_prec_expr | higher_prec expr ## for left-associative ops: ## warning: written this way, it is left-recursive. lower_prec_expr : lower_prec_expr lower_prec_op higher_prec_expr | higher_prec expr
You will have many layers of this type of thing (one for each level of precedence). You can think of it as the grammar matching the outermost expressions first (which have the lowest precedence, so are conceptually applied last), and then filling in the higher-precedence details later.

Here's an example for your purposes:

use Parse::RecDescent; use Data::Dumper; my $grammar = q{ startrule: logical_expr logical_expr: comparison_expr logical_op logical_expr { [@item[1,2,3 +]] } | comparison_expr logical_op: /\\|\\||or|&&|and/ comparison_expr: paren_expr comparison_op comparison_expr { [@item[1 +,2,3]] } | paren_expr comparison_op: />=?|<=?|!=|==|le|ge|eq|ne|lt|gt/ paren_expr: '(' logical_expr ')' { $item[2] } | atom atom: /[A-Za-z_][A-Za-z0-9_]*/ }; my $parser = new Parse::RecDescent $grammar; for (<DATA>) { print $_; print Dumper $parser->startrule($_); print "============\n"; } __DATA__ foo == bar || baz < bar foo == bar || baz < bar || foo && bar (foo || bar) || baz
This seems to output the kind of thing you want. Notice how paren_expr must refer all the way back to the lowest-level precedence logical_expr!

Postscript: Refer to the Dragon Book or a similar parsing reference for more on stratification. (could have sworn the Dragon Book mentioned this, but it's not in the index)

Update: Limbic~Region noticed that I had swapped left & right associativity in my examples. Now fixed.