glwtta has asked for the wisdom of the Perl Monks concerning the following question:

Trying to learn how to use Parse::RecDescent I thought I'd pick something simple - parse (and graph) boolean expressions. So far I have:
my $grammar = q { { my $g = GraphViz->new } start: expression /$/ { $return = $g } expression: item_right_exp | right_exp | item right_exp: operator expression {$return = $g->add_node($it +em[1]);$g->add_edge($return, $item[2]);} item_right_exp: item operator expression {$return = $g->ad +d_node($item[1].'-'.$item[2].'-'.$item[3], label => $item[2]);$g->add +_edge($return, $item[1]);$g->add_edge($return, $item[3]);} operator: 'AND' | 'OR' item: 'NOT' item | multi_word | word {$return = $g->add_no +de($item[1]);} multi_word: '"'word(s)'"' {$return = join(' ', @{$item[2]} +); } word: /[a-zA-Z\?\*]+/ };
Is this kinda going in the right direction? The next step would be to add parenthesis and I am at a bit of a loss as to how to do that.

As I am very new at this any advice greatly appreciated.

Replies are listed 'Best First'.
Re: Parse::RecDescent and boolean expressions
by liz (Monsignor) on Aug 10, 2003 at 12:14 UTC
•Re: Parse::RecDescent and boolean expressions
by merlyn (Sage) on Aug 10, 2003 at 19:50 UTC
    Your grammar appears sideways. You're permitting "AND foo" as a legal construct, for example.

    Off the top of my head, the traditional grammar for an expression looks more like:

    expression: <leftop: exp1 'OR' exp1> exp1: <leftop: exp2 'AND' exp2> exp2: ('NOT')(s?) exp3 exp3: item | '(' expression ')' item: ...
    This also gets all the precedence right. You're not going to be able to parse "AND" and "OR" in the same rule and get the precedence right.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Parse::RecDescent and boolean expressions
by jeffa (Bishop) on Aug 10, 2003 at 15:13 UTC