Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Evaluate arbitrary boolean expressions

by choroba (Cardinal)
on Mar 13, 2018 at 17:44 UTC ( [id://1210838]=note: print w/replies, xml ) Need Help??


in reply to Evaluate arbitrary boolean expressions

If you don't want to use eval for security purposes, write a parser. Marpa::R2 is a module that can help you with that:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use Marpa::R2; my $dsl = << '__DSL__'; :default ::= action => ::first lexeme default = latm => 1 Exp ::= Term | Exp (disj) Term action => disj Term ::= Factor | Term (conj) Factor action => conj Factor ::= Atom | Negation | Bracketed Bracketed ::= (lbra) Exp (rbra) Negation ::= (excl) Factor action => neg Atom ::= true action => true | false action => false true ~ 'T' false ~ 'F' excl ~ '!' conj ~ '&&' disj ~ '||' lbra ~ '(' rbra ~ ')' ws ~ [\s]+ :discard ~ ws __DSL__ sub true { 1 } sub false { 0 } sub neg { ! $_[1] } sub conj { $_[1] && $_[2] } sub disj { $_[1] || $_[2] } my $grammar = 'Marpa::R2::Scanless::G'->new({source => \$dsl}); my $input = '((T) || (!(T))) && !(F && F && F && F && ! (T))'; my $value = ${ $grammar->parse(\$input, 'main') }; say $value ? 'TRUE' : 'FALSE';

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2025-01-23 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which URL do you most often use to access this site?












    Results (63 votes). Check out past polls.