http://qs321.pair.com?node_id=1004675

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

Hi monks, say I have a file with conditions for if statements, for example
($a>50) ($b==20) ($c eq 'cat')
I want to read the file, and do the if statements, something like this
use strict; use warnings; { my $a = 20; my $b = 20; my $c = 'dog'; open IN, "<", 'input.txt' or die "can't open file\n"; while (my $line = <IN>){ my $statement = $line; chomp ($statement); print "$statement\n"; ##Confusing if ($statement){ print "true\n"; } } }
The problem, of course, is that "if $statement" will be true when $statement is not null (always). What I want is a dynamic if statement, according to the input file, which will only print true for the second statement.
Any ideas how this can be done?
Thanks, Mister Guy

Everybody seems to think I'm lazy
I don't mind, I think they're crazy

UPDATE: Added eval to the code and it works like a charm. Thanks for the help

Replies are listed 'Best First'.
Re: Get condition for "if statement" from file
by Utilitarian (Vicar) on Nov 20, 2012 at 08:51 UTC
    You need to evaluate the statements as though they were part of your program rather than data:
    #!/usr/bin/perl use strict; use warnings; { my $a = 20; my $b = 20; my $c = 'dog'; open IN, "<", 'tmp/tmp.dat' or die "can't open file\n"; while (my $line = <IN>){ my $statement = $line; chomp ($statement); print "$statement\n"; ##Less confusing? if (eval($statement)){ print "true\n"; } } }
    WARNING eval is a HUGE security risk and anything can happen if you don't have rigid control over the input
    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
      Worked like a charm, thanks for your help!!
Re: Get condition for "if statement" from file
by McA (Priest) on Nov 20, 2012 at 08:49 UTC

    Hi,

    look at perldoc -f eval where the parameter is a string. It should help.

    Best regards
    McA