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


In reply to Re: prefix notation in an array by tsee
in thread prefix notation in an array by amw1

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.