in reply to How to set relational operators to variables to be used by program

I just skimmed through your code and then the question at the end. It seems you wish to avail the "dynamic operator" functionality.
Please check if the following code serves your purpose.
$num1=10; $num2=20; for $op ("<",">","==") { if(eval "$num1 $op $num2") { print "\n$num1 $op $num2 is TRUE"; } else { print "\n$num1 $op $num2 is FALSE"; } } #---------------OUTPUT----------- 10 < 20 is TRUE 10 > 20 is FALSE 10 == 20 is FALSE
  • Comment on Re: How to set relational operators to variables to be used by program
  • Download Code

Replies are listed 'Best First'.
Re^2: How to set relational operators to variables to be used by program
by dkhalfe (Acolyte) on Jul 19, 2012 at 16:27 UTC
    for my $op ($filter [0]->[1]) { if (eval "$hash{$filter[0]->[0]} $op $filter[0 +]->[2]") { print OUTFILE $line, "\n"; } }

    This seems to work. Thanks! If any one else has other suggestions please inform!

      The usual warning: If you use eval, you have to make sure that either no evildoer can put any code into the file where the opcodes are stored or that you check the values with regexes so that only acceptable ops get through

      And something else: If you use $hash{$filter[0]->[0]} inside the eval string, it is substituted with its value as well. This is fine as long as you want to compare numbers, because (10 < 20) is a valid comparision expression in perl, but if you want to also compare strings, for example "blue" and "green", then the eval will fail because (blue lt green) is not a valid expression, it should be ("blue" lt "green"). Solution: Escape the operands like this: \$hash{\$filter[0]->[0]}

      And your example filter 3 (for column b) is wrong, '=' is assignement, '==' is equality (which would suggest that a regex to check for correct relationships/operators might not be a bad idea anyway)

        How would I go about checking the vlaues with regexes?

      For that matter, you can also write:
      if (eval "$hash{$filter[0]->[0]} $filter [0]->[1] $filter[0]->[2]") { print OUTFILE $line, "\n"; }
      eliminating the extra for loop.