I've lately begun to explore Parse::RecDescent and have a couple of questions. Given:

#!/usr/bin/perl # parse.pl -- learning Parse::RecDescent ex. use strict; use warnings; use diagnostics; use Parse::RecDescent; my $parser = new Parse::RecDescent( q{ startrule: calculation eofile {$return = $item[1];} statement: grouped_op | number grouped_op: '(' calculation ')' {$return = $item[2];} calculation: add_calculation | sub_calculation | mul_calculation | + div_calculation add_calculation: statement '+' statement {$return = $item[1] + $it +em[3];} sub_calculation: statement '-' statement {$return = $item[1] - $it +em[3];} mul_calculation: statement '*' statement {$return = $item[1] * $it +em[3];} div_calculation: statement '/' statement {$return = $item[1] / $it +em[3];} number: /\d+/ eofile: /^\Z/ }); my @tests = ( '4 + 8', '6 + (3 - 2)', '(6 + (3 - 2)) + 1', '4 + 8 + 5', '5 * 5', '5 / 5', ); my $result; foreach my $test (@tests) { if ( $result = $parser->startrule($test) ) { print "'$test' = $result\n"; } else { print "'$test' failed parser\n"; } }
It's clear that the parentheses work, my first question is why does the lack fail? '4 + 8 + 5' working from left to right should collapse into '12 + 5' and then to '17'. Obviously using $::RD_TRACE = 1; shows that it gets as far as '12', but then fails after that. I'm fairly sure this is a beginner's error but it doesn't leap out at me.

Looking ahead, I'd want to implement some sort of precedence scheme. Pointers, brickbats and suggestions gratefully accepted!

–hsm

"Never try to teach a pig to sing…it wastes your time and it annoys the pig."

In reply to Parse::RecDescent without parentheses by hsmyers

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.