in reply to Backtracking in Parse::RecDescent

After digging into the Parse::RecDescent docs, I found out that the mechanism to alter Parse::RecDescent's preference for the first match is the <score: ...> directive. The code below illustrate how it solves your case.

use strict; use warnings; use Parse::RecDescent; my $grammar = q/ startrule: choice "a" choice: "a" "a" <score: -2> | "a" <score: -1> /; my $parser = Parse::RecDescent->new($grammar); while (<DATA>) { chomp($_); print defined($parser->startrule($_)) ? "Good!\n" : "Bad!\n"; } __DATA__ a a a a a
Now the result is "Good!" for both 'a a a' and 'a a' as desired

Hope this helps, -gjb-

Replies are listed 'Best First'.
Re: Re: Backtracking in Parse::RecDescent (solution)
by ruscoekm (Monk) on Dec 06, 2002 at 22:50 UTC
    Thanks, that's a good answer. However, it does not quite do what I want, which is for the parser to try all possible alternatives in a production before failing. I suspect that the answer is that top-down parsers just do not work that way.
      The answer is that RecDescent parsers do not work that way. They don't backtrack on failure; they just fail. Of course, there's nothing to prevent a recursive descent parser from incorporating backtracking too, but RecDescent doesn't.

      So, if you need backtracking in part of your grammar, you need to use plain old regexes there. Sorry.

      Damian

        Thanks Damian. It's one thing to suspect an explanation; quite another to have it confirmed :)

        Kevin