Alex Rivera | Logout

How can I "store" an operator inside a variable in Perl?

Asked 2010-03-21T09:44:05.883
9

I'm looking for a way to do this in Perl:

$a = "60"; $b = "< 80";

if ( $a $b ) {  then .... }

Here, $b "holds" an operator... can I do this? Maybe some other way?

Edit
Report

1 Answer

8

This should be a comment but comments are too cramped for something like this so I am making it CW.

For the case which you showed where the contents of the variables that are going to be passed to string eval, the accepted solution is correct.

If, however, the contents of $a and $b come from user input, then take a look at the following script:

#!/usr/bin/perl

use strict; use warnings;

my $x = '80';
my $y = '; warn "evil laugh!\n"; exit';

if ( eval ($x . $y) ) {
    print "it worked!!!\n";
}

If the strings are entered by the user, there is nothing preventing the user from passing to your program the string ';system "rm -rf /bin"'.

So, the correct solution to your question would require writing or using an expression parser.

BTW, you should not use $a and $b as variable names as the are magical package local variables used by sort and as such they are exempt from strict — and you must always use strict and warnings in your programs.

answered 2010-03-21T13:18:35.953

Your Answer