in reply to prefix notation in an array
Update: I am so sorry. I didn't read your post thoroughly enough. This is actually an infix-expression parser. I posted code that solves your problem in a reply to this post. -- Steffen
The following code should solve your problem including operator precedence (and > or > == > !).
Note, however, that it will be very slow when dealing with long strings.
use strict; use warnings; use Data::Dumper; use Parse::RecDescent; my $grammar = <<'GRAMMAR'; boolean_expr: and_expr { $item[1] } | terminal { $item[1] } | <error> and_expr: <leftop: or_expr 'and' or_expr> { my $ary = $item[1]; my $return = $ary->[0]; foreach (@{$ary}[1..$#$ary]) { $return = ['and', $return, $_]; } $return; } or_expr: <leftop: eq_expr 'or' eq_expr> { my $ary = $item[1]; my $return = $ary->[0]; foreach (@{$ary}[1..$#$ary]) { $return = ['or', $return, $_]; } $return; } eq_expr: <leftop: unary_expr '==' unary_expr> { my $ary = $item[1]; my $return = $ary->[0]; foreach (@{$ary}[1..$#$ary]) { $return = ['==', $return, $_]; } $return; } unary_expr: '!' term { ['!', $item[2]] } | term { $item[1] } term: '(' boolean_expr ')' { $item[2] } | terminal { $item[1] } terminal: /\w+/ { $item[1] } GRAMMAR my $parser = Parse::RecDescent->new($grammar); while (<STDIN>) { chomp; my $parsed; $parsed = $parser->boolean_expr($_); next unless defined $parsed; print Dumper $parsed; }
For a more involved example of a Parse::RecDescent grammar for parsing similar expressions, have a look at the Math::Symbolic::Parser module (algebraic expressions in that case).
Steffen
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: prefix notation in an array
by tsee (Curate) on Mar 26, 2004 at 15:18 UTC | |
|
Re: Re: prefix notation in an array
by amw1 (Friar) on Mar 26, 2004 at 15:43 UTC |