I am writing a parser that takes a user-specified string and evaluates the tokens within it. A token in this case meaning an expression grouped within parentheses. The idea is to take one string, and recursively replace each token with its evaluated value. So, (2 > 1) would be replaced with 1. This would allow any combination of tokens to be grouped into a string of nested parentheses, and then be parsed.
The code that follows does this quite well...up until the very last replacement, when there is just one token left. And as a result, I'm rather puzzled. This is a test case of code, written to output what it's doing.
#! /usr/bin/perl
#sample string.
$string = "((2 > 1) | ('word' eq 'toy'))";
#next line converts user-specified operators into Perl
#logical operators.
$string =~ s/([&|]{1})/$1$1/g;
print "Initial parsed string = $string\n";
#Look ahead assertion.
while ($string =~ /\(((?:[^()])*?)\)/) {
my $val = (eval $1) ? 1 : 0;
print "Case to be evaluated = $1\n";
print "Evaluated value = $val\n";
$string =~ s/\($1\)/$val/;
print "Parsed string = $string\n";
}
print "Result: $string\n";
The code as shown above will end with 1|| 0), instead of just 1. However, if I change the | to & in the test string? It works fine. Which puzzles me to no end.
So Great Monks, whose wisdom far outstrips mine own...how do I make this work more consistently?
~Moe~
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.