in reply to Re: eval question
in thread eval question

I second your suggestion. Parse::RecDescent would work for this (recently figured that one out too) but in this case, the above example will work well for simple calculations.

However - what if you need to do something that involves precedence? i.e. -
1 + 9 * ( 60 / 5 )

What is the recommended path there?

Replies are listed 'Best First'.
Re^3: eval question
by ikegami (Patriarch) on Apr 16, 2007 at 15:19 UTC
Re^3: eval question
by liverpole (Monsignor) on Apr 16, 2007 at 15:11 UTC
    I'll confess that I haven't used Parse::RecDescent ... a need for it hasn't yet arisen.

    If you were doing something complicated (eg. your precedence problem), my first inclination would be to use eval, but only after validating that the input was sane.  For example:

    #!/usr/bin/perl -w use strict; use warnings; # Test data my $string = "1 + 9 * ( 60 / 5 )"; # Validate if ($string !~ m:^[-+*/()0-9.\s]+$:) { die "Bad input '$string'\n"; } my $result = eval $string; print "Result of '$string' = $result\n";

    But I don't know offhand if that's the best way to do it, or what other caveats you might run into.

    Update:  Fixed the regexp.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/