Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Generate a truth table from input string

by moritz (Cardinal)
on May 13, 2008 at 10:58 UTC ( #686287=note: print w/replies, xml ) Need Help??

in reply to Generate a truth table from input string

Ah well, what stops you?

You could of course look to cpan to see if there's anything that can help you.

If you want to parse the string yourself, take a look at RFC: Parsing with perl - Regexes and beyond and perhaps at Parse::RecDescent.

Evaluation should be pretty simple once you have a parse tree.

  • Comment on Re: Generate a truth table from input string

Replies are listed 'Best First'.
Re^2: Generate a truth table from input string
by tachyon-II (Chaplain) on May 13, 2008 at 11:35 UTC

    Parsing is quite possibly not required. Assuming that the variables can be assumed to contain a true value why not just leverage perl.

    $str =~ s/\*/&&/g; $str =~ s/\+/||/g; # $str =~ s/'/!/g; $str =~ s/(\w+)'/!$1/g; $str =~ s/\(([^\)]+)\)'/!($1)/g; $str =~ s/\w+/1/g; my $truth = eval $str;

    If the a/b/A/B vars have associated values all that is required is to substitute them in. Perl does the parsing and calculates the truth.


    Modified to deal with ' postfix syntax

      $str =~ s/'/!/g;
      is not sufficient to convert a postfix operator to a prefix operator. "a'" produces the invalid code "1!".
        $str =~ s/(\w+)'/!$1/g; $str =~ s/\(([^\)]+)\)'/!($1)/g;
Re^2: Generate a truth table from input string
by Anonymous Monk on May 13, 2008 at 11:07 UTC
    the problem that i am facing is, NOT is represented by both ! and ', variables could be !(A)+!(B)+!(C) or A'+B'+C', both mean the same. how do i do it?


      Rule One: Do not act incautiously when confronting a little bald wrinkly smiling man.
        or as use warnings; would say...
        \1 better written as $1

        and use diagnostics; would elaborate...

        (W syntax) Outside of patterns, backreferences live on as variable +s. The use of backslashes is grandfathered on the right-hand side of +a substitution, but stylistically it's better to use the variable fo +rm because other Perl programmers will expect it, and it works better + if there are more than 9 backreferences.
        Is (a+b)' disallowed?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://686287]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2021-06-19 21:33 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (93 votes). Check out past polls.