in reply to eval question
^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.
|
|---|