If you trust that the data you're getting is well-formed, you can just use eval. Perl's boolean operators and precedence just happens to be exactly what you've defined, so why not let perl do the work? Taking that approach, it's pretty trivial to suck out the variable names from that expression and then make a truth table ..
my $bool_func = "((S0*B)|((!S0)*A))"; (my $perl_expr = $bool_func) =~ s/([a-zA-Z]\w*)/\$val{$1}/g; print "Using perl expression: $perl_expr\n"; my @vars = do { my %seen; grep !$seen{$_}++, $bool_func =~ /([a-zA-Z]\w*)/g; }; for my $assignment ( 0 .. (2**@vars)-1 ) { my %val; $val{$vars[$_]} = ( $assignment >> $_ ) & 1 for 0 .. $#vars; my $result = eval $perl_expr; print join(", ", map { "$_=$val{$_}" } keys %val), " ==> $bool_func=$result\n"; } __END__ Using perl expression: (($val{S0}*$val{B})|((!$val{S0})*$val{A})) A=0, S0=0, B=0 ==> ((S0*B)|((!S0)*A))=0 A=0, S0=1, B=0 ==> ((S0*B)|((!S0)*A))=0 A=0, S0=0, B=1 ==> ((S0*B)|((!S0)*A))=0 A=0, S0=1, B=1 ==> ((S0*B)|((!S0)*A))=1 A=1, S0=0, B=0 ==> ((S0*B)|((!S0)*A))=1 A=1, S0=1, B=0 ==> ((S0*B)|((!S0)*A))=0 A=1, S0=0, B=1 ==> ((S0*B)|((!S0)*A))=1 A=1, S0=1, B=1 ==> ((S0*B)|((!S0)*A))=1
I hope it goes without saying that if you aren't this confident about the state of your input, your solution needs to involve parsing (and therefore validating) the input expression -- either explicitly, or by means of an existing modular solution.

blokhead


In reply to Re: parser for evaluating arbitrarily complex boolean function in a string by blokhead
in thread parser for evaluating arbitrarily complex boolean function in a string by jce

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.