I am trying to put together a Parse::RecDescent grammar that will read in an expression and build a parse tree for it. So far things have gone pretty well, but the order of precedence is not working for me. My test case shows multiplication having a higher precedence than modulus, which is wrong... Here is the test script
use strict; use Parse::RecDescent; use Data::Dumper; my $grammar = q` startrule: expression /^\Z/ { $item[1]; } # you can also put comments into the grammar # such as to explain that /^\Z/ means 'match the end of the string +' expression: operand operator expression { [@item[1..3]] } | operand { $item[1] } number: /\d+/ { $item[1] } paren_expression: '(' expression ')' { $item[2] } operand: paren_expression { $item[1] }| number { $item[1] } operator: '%' { [@item] } | /[*\/]/ { [@item] } | /[+-]/ { [@item] } | '=' { [@item] } `; my $parser = new Parse::RecDescent( $grammar ) or die "Compile error\n +"; my $st = '3%2*4'; print Dumper($parser->startrule($st)); ##### Printout $VAR1 = [ '3', [ 'operator', '%' ], [ '2', [ 'operator', '*' ], '4' ] ];
evaluating this would give the equivalent of 3%(2*4) which is wrong. I am new to P::RD so I am sure I have just done something stupid along the way... any enlightenment would be much appreciated.

                - Ant
                - Some of my best work - (1 2 3)


In reply to Order of Precedence in Parse::RecDescent grammar by suaveant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.