Building on AnonyMonk's approach above (and this actually works):
c:\@Work\Perl>perl -wMstrict -MData::Dump -le
"use constant OPS => qw{ ( ( ) ) ! ! | || & && };
;;
sub compile {
my ($expr, $hr_vars) = @_;
;;
my %xlate = (OPS, %$hr_vars);
;;
$expr =~ s{ (.) }
{ exists $xlate{$1}
or die qq{bad: '$1' at offset $-[1] in '$expr'};
$xlate{$1};
}xmsge;
;;
return $expr;
}
;;
my %vars = qw(Q 0 T 1 C 0);
dd \%vars;
;;
my $expr = '(!(C)&T)&!Q';
print qq{initial expr: '$expr'};
;;
my $final_expr = compile($expr, \%vars);
print qq{ final expr: '$final_expr'};
;;
my $result = eval $final_expr;
if ($@) {
print qq{eval of '$final_expr' failed: $@}
}
else {
print qq{'$final_expr' -> '$result'};
}
"
{ C => 0, Q => 0, T => 1 }
initial expr: '(!(C)&T)&!Q'
final expr: '(!(0)&&1)&&!0'
'(!(0)&&1)&&!0' -> '1'
Some thoughts:
-
Caution: Because it uses string eval, this code is not guaranteed to be safe, whatever your definition of "safe" may be. Caveat programmor.
-
Play with this. E.g., are the outputs of '(x!(C)&T)&!Q' or '(!(C(&T)&!Q' acceptable?
-
The expression !1 evaluates to '' (the empty string), which can propagate through subsequent logical expressions to produce an empty string as output, so after all you may want the bitwise | & operators, which can produce 0 1 outputs.
-
This code works under ActiveState 5.8.9 and should work, but has not been tested, under any higher Perl version.
Give a man a fish: <%-{-{-{-<
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.