in reply to Re^2: How to pass a variable string as conditional argument to if statment
in thread How to pass a variable string as conditional argument to if statment

I'd actually recommend using anonymous subroutines much more than eval for something like this. Would change your code to the following:

#!/usr/bin/perl -w use strict; use warnings; my $hash_ref1 = { this => 'blarney', some => 'foo', chancy => 'at best', }; my $hash_ref2 = { this => 'that', some => 'thing', another => 'something', }; print "this is $hash_ref2->{this}\n"; my @a = ($hash_ref1, $hash_ref2); my $test = sub {$_->{this} eq 'that'}; foreach (@a) { if ($_->{this} eq 'that') { print qq{I only want to see case where: "this really does equa +l $_->{this}"\n}; } if ($test->()) { print "this really does equal $_->{this}\n\n"; } }

Or if you don't want to rely on the $_ variable, you can pass the variable as a parameter to the sub:

my $test = sub {$_[0]->{this} eq 'that'}; foreach my $hash_ref (@a) { if ($hash_ref->{this} eq 'that') { print qq{I only want to see case where: "this really does equa +l $hash_ref->{this}"\n}; } if ($test->($hash_ref)) { print "this really does equal $hash_ref->{this}\n\n"; } }

Replies are listed 'Best First'.
Re^4: How to pass a variable string as conditional argument to if statment
by Anonymous Monk on Feb 05, 2016 at 20:32 UTC
    Hi, I have a variable $var = '10>5"; This string is obtained from a table and is stored in the variable. I want to evaluate this string. If it is true, then execute. E.g, if($var is true){ }else { } I tried to use eval but is not working as expected.

      Are you checking for errors after the eval ?

      #!perl use strict; my @test = ('10>5','10<5','13+2==14+1','4>(6/2)+1'); for my $var (@test){ my $result = eval $var ? 'True' : 'False'; die $@ if $@; # check for errors in eval print "$var is $result\n"; }
      poj
      You should validate the string before running eval on it. Imagine the string contains
      system 'rm -rf /'

      or something similar.

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,