开发者

Is there a good tool to parse/evaluate mathematical expressions?

开发者 https://www.devze.com 2023-02-26 18:56 出处:网络
Argghh: $ echo 2 4 | bc (standard_in) 1: parse error $ echo $? 0 Why on earth would an otherwise perfectly reasonable program succeed when it recognizes a parse error?Clearly, I cannot use bc to e

Argghh:

$ echo 2 4 | bc
(standard_in) 1: parse error
$ echo $?
0

Why on earth would an otherwise perfectly reasonable program succeed when it recognizes a parse error? Clearly, I cannot use bc to evaluate an expression. Personally, I like dc, but my users do not want reverse p开发者_高级运维olish. Given an arithmetic expression of the form that bc recognizes, is there a reasonable program for evaluating the result? Or is there a way to make bc reasonable? (Here, "reasonable" means that it fails when the input is bogus.)


bc will try to recover from errors, and keep processing later statements. For example:

$ echo "2 + 3; 
    4 4;
    3 + 4" | bc
5
(standard_in) 2: parse error
7

Thus, it's not clear if it should return an error in that case. It successfully parsed and processed the input, correctly recovering from the error and continuing to process later instructions. According to POSIX, the behavior of bc is undefined when invalid input is detected in non-interactive mode, so this is within the specification of how bc should behave.

If you want to test if there were any errors while processing your input, you can redirect stderr to a temporary file, and then check the contents of that to look for errors:

bcerr=$(mktemp -t bcerr)
result=$(echo 2 4 | bc 2>$bcerr)
if test -s $bcerr
then
  # handle errors
else 
  # handle success
fi
rm $bcerr


You can catch the error from bc by looking at the stderr output, or by just redirecting stderr to /dev/null and recognizing when the output is empty:

answer=$(echo "$expression" | bc 2>/dev/null)
if [ -z "$answer" ]; then
    echo "error in $expression"
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消