Perl for calculating an expression.

Discussion in 'Perl Misc' started by syang8, Jul 23, 2008.

  1. syang8

    syang8 Guest

    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
     
    syang8, Jul 23, 2008
    #1
    1. Advertisements

  2. 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
     
    Jürgen Exner, Jul 23, 2008
    #2
    1. Advertisements

  3. [A complimentary Cc of this posting was NOT [per weedlist] sent to
    Jürgen Exner
    Here are my aliases (4dos and tcsh):
    pprint -e "print {STDOUT} %&"
    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
     
    Ilya Zakharevich, Jul 23, 2008
    #3
  4. 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
     
    Jürgen Exner, Jul 23, 2008
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.