Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Eliminating the common prefix from a Parse::RecDescent rule

by Dirk80 (Pilgrim)
on Sep 02, 2010 at 22:27 UTC ( #858642=note: print w/replies, xml ) Need Help??

in reply to Eliminating the common prefix from a Parse::RecDescent rule
in thread Operator Associativity and Eliminating Left-Recursion in Parse::RecDescent

Thank you for this great tutorial. This was a very helpful introduction.

I tried to play a bit with your example. In the following code I do not get the Error "Bad Expression" for my second expression although it is not valid.

use strict; use warnings; use Parse::RecDescent (); my $grammar = <<'__END_OF_GRAMMAR__'; { use strict; use warnings; } { sub eval_sum { my $acc = shift(@_); while (@_) { my $op = shift(@_); if ($op eq '+') { $acc += shift(@_); } elsif ($op eq '-') { $acc -= shift(@_); } } return $acc; } } sum : NUM sum_ { eval_sum( ($item[1], @{$item[2]}) ) } sum_: /[+-]/ NUM sum_ { $return = [$item[1], $item[2], @{$item[3]}] +} | { $return = [] } NUM : /\d+/ { $return = $item[1] } __END_OF_GRAMMAR__ my $parser = Parse::RecDescent->new($grammar) or die("Bad grammar\n"); foreach my $expr ('4-5+6-2','4*5') { my $sum = $parser->sum($expr) or die "Bad expression"; print "$sum" . "\n"; }

Why do I not get the "Bad expression" error for my second expression?

Thank you


Replies are listed 'Best First'.
Re^2: Eliminating the common prefix from a Parse::RecDescent rule
by ikegami (Patriarch) on Sep 03, 2010 at 02:15 UTC
    You must check that nothing follows what sum matches.
    evaluate : sum /\Z/ { $item[1] } ->evaluate($expr)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://858642]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2022-01-23 03:40 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (63 votes). Check out past polls.