Perl for calculating an expression.


S

syang8

Is there any peal script available that I can quickly calculate a
string " (3+5)*5/40 " or " 4*7-7*(4+5) " ? There are only the digits
and +,-,*,/ and () available in the string. Thank you!

-Steve
 
Ad

Advertisements

J

Jürgen Exner

syang8 said:
Is there any peal script available that I can quickly calculate a
string " (3+5)*5/40 " or " 4*7-7*(4+5) " ? There are only the digits
and +,-,*,/ and () available in the string. Thank you!

Is quick and dirty good enough? Then just use eval().

Otherwise writing a simple parser and interpreter for such a tiny
language is a favourite second semester excercise.

jue
 
I

Ilya Zakharevich

[A complimentary Cc of this posting was NOT [per weedlist] sent to
Jürgen Exner
Is quick and dirty good enough? Then just use eval().

Otherwise writing a simple parser and interpreter for such a tiny
language is a favourite second semester excercise.

Here are my aliases (4dos and tcsh):
alias pprint
pprint -e "print {STDOUT} %&"
alias _pprint
perl -wle "sub atan($) {atan2 shift, 1} sub tan($) {sin($_[0])/cos($_[0])} sub pi () {atan2 0, -1} sub e() {exp 1} sub h() {'6.62607e-34'} sub eV() {'1.6021765e-19'} sub G() {6.674e-11} sub N() {6.022142e23} sub c() {299792458} sub R() {8.314472} sub k() {R/N} $, = q(, ); "

->alias pprint
perl -wle '$, = q(, ); print(!:1*)'

Hope this helps,
Ilya
 
Ad

Advertisements

J

Jürgen Exner

Glenn Jackman said:
At said:
Is there any peal script available that I can quickly calculate a
string " (3+5)*5/40 " or " 4*7-7*(4+5) " ? There are only the digits
and +,-,*,/ and () available in the string. Thank you!

$str =~ m{^([\s\d()/*+-]+)$} and $result = eval $1;

This does not check that your expression is "well formed" (e.g. $str="1+")

Yes, it does:

If there is a syntax error or runtime error, [...],
an undefined value is returned by "eval", [...]

The code doesn't doesn't do any error handling, but that's a different
animal.

jue
 

Top