in reply to eval question

Is it possible to do $r = eval("$a $op $b")

In principle yes, if you map the operators 'le', 'ge' etc. to the corresponding Perl equivalents — e.g. using a hash.

my %perlop = ( le => '<=', ge => '>=', #... ); my $r = eval "$a $perlop{$op} $b";

(But as always with string eval, be careful what you interpolate when the data ($a, $b here) doesn't come from trusted sources...)

Replies are listed 'Best First'.
Re^2: eval question
by moritz (Cardinal) on Jan 06, 2011 at 19:59 UTC
    (But as always with string eval, be careful what you interpolate when the data doesn't come from trusted sources...)

    If you whitelist allowed operators via hash, and don't interpolate $a and $b, you should be fine:

    if (exists $perlop{$op}) { my $r = eval "\$a $perlop{$op} \$b"; } else { die "OH NOEZ!"; }

    That way the string passed to eval contains the variable names, and obtains their value from the outer scope.