Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I just discovered the pragma 're' and I'm inetersted in using it. If I had the string:
my $question="67.35 >= 50 && 67.35 < 80";
How would I complete the ev routine?
#!C:/perl/bin/perl.exe use warnings; use strict; use re 'eval'; my $question="67.35 >= 50 && 67.35 < 80"; my $ans=ev($question); print "ans=$ans\n"; sub ev { ... ? }

Or is there a better way?

Replies are listed 'Best First'.
Re: using re 'eval' for varibable math
by ikegami (Patriarch) on Apr 19, 2005 at 14:59 UTC

    That's not a regexp, so the re pragma won't help here. However, the built-in eval function will:

    #!C:/perl/bin/perl.exe use warnings; use strict; my $question = "67.35 >= 50 && 67.35 < 80"; my $ans = eval $question; die("Compile error: $@\n") if $@; print("ans = ", ($ans ? 'true' : 'false'), "\n");

    Beware including user-supplied data in an eval. Users are sometimes malicious or supply unexpected data.

      Much easier....That works great. Thanks!
Re: using re 'eval' for varibable math
by tall_man (Parson) on Apr 19, 2005 at 20:53 UTC
    The Math::Pari module can evaluate mathematical expressions with a more restricted syntax than perl's -- but watch out for "system()". Here's an example.
    use strict; use Math::Pari qw(PARI); my $question="67.35 >= 50 && 67.35 < 80"; # Pari doesn't like white space in expressions. $question =~ s/\s+//g; my $out = PARI $question; print $out,"\n";
Re: using re 'eval' for varibable math
by salva (Canon) on Apr 19, 2005 at 15:55 UTC
    as ikegami toll you, eval $expr is the easiest way to evaluate arithmetic expresions but it allows for more things that just math, so it can be very dangerous.

    You can try checking the expression first with a regular expression but you have to be very carefull, and finding a secure filter for more than simple math expressions becomes difficult.

    Other alternative is to write a parser and an evaluator in perl. The parser converts the string to a tree (or stack or other conveniant representation) and after that, the evaluator evaluates it (look in CPAN for Parser::RecDescent for an easy way to write parsers).