^I *nix has a maths expression calculator called bc.

^P Piping the input to bc is completely safe.

^B But bc doesn't use real-numbered division and will reject brackets and most maths function calls.

^C You could write a very simple parser that looks only for identifiers (make a hash of valid maths. function names to check against) and brackets and replaces them with 1 just to submit to bc to check the rest of the expression syntax, using also bc to check the syntax inside each bracketed expression (need to recusively parse the brackets). Such a parser should only be a few lines of code, so ask for further advice if you are generating more than say half a page for that. To submit to bc, use e.g. IPC::Open3 and just check if anything comes back on the error channel.

The point of the algorithm is: If there is nothing left after eliminating expected function calls, bracketed expressions, their 1-modified contents being validated by bc and finally the outer 1-modified expression is also validated by bc, then it's okay to go ahead and eval the (unmodified!) expression.

The wrapper for checkbc would look something like:

sub CheckBC { my $pid = open3 my $wh, my $rh, my $eh, "bc" or die; print $wh shift() . "\n"; close $wh or die; my $throwResultAway = <$rh>; close $rh or die; my $error = <$eh>; close $eh or die; waitpid $pid, 0; # else forkbomb, zombies, etc. !$error; }
__________________________________________________________________________________

^M Free your mind!

Key to hats: ^I=white ^B=black ^P=yellow ^E=red ^C=green ^M=blue - see Moron's scratchpad for fuller explanation.


In reply to Re: eval question by Moron
in thread eval question by Anonymous Monk

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.