Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Get condition for "if statement" from file

by mrguy123 (Hermit)
on Nov 20, 2012 at 08:41 UTC ( #1004675=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on Get condition for "if statement" from file
Select or Download Code
Re: Get condition for "if statement" from file
by McA (Curate) 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

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!!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1004675]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2014-09-21 08:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls