hsmyers has asked for the wisdom of the Perl Monks concerning the following question:
I've lately begun to explore Parse::RecDescent and have a couple of questions. Given:
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.#!/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"; } }
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."
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parse::RecDescent without parentheses
by maverick (Curate) on Feb 03, 2002 at 19:58 UTC | |
by merlyn (Sage) on Feb 04, 2002 at 05:19 UTC | |
by maverick (Curate) on Feb 04, 2002 at 07:57 UTC | |
|
Re: Parse::RecDescent without parentheses
by jmcnamara (Monsignor) on Feb 03, 2002 at 22:24 UTC | |
|
Re: Parse::RecDescent without parentheses
by dreadpiratepeter (Priest) on Feb 03, 2002 at 20:20 UTC |