views:

474

answers:

3

In Perl, I need to read a .conf file that contains either a 0 or a 1. If the value is one, I need to execute whatever is in the if statement. Here is what I have now:

open(CONF, "/var/web/onhit.conf");
if(<CONF>) {
   print "Hello World!";
}
close(CONF);

The contents of the if statement always evaluate, even if the .conf file contains a 0. I know the file reading is correct because this code can read the file correctly:

open(CONF, "/var/web/onhit.conf");
print <CONF>;
close(CONF);

If the file contains a 1, it prints a 1, and vice versa. Does anyone know what is wrong with my first snippet? Sorry, but I am a n00b at Perl. :-)

+5  A: 

EDIT: Apparently, you had the truth value of your post inverted, and you meant to say that the if() statement always executed. This makes sense. What happens is that <CONF> reads in the string "1\n" or "0\n", not the number 1 or 0. The trailing newline prevents "0" from evaluating as false, so you need to chomp() it (or use the int() function, as mentioned in the other post). Either way should work.

(Note that, unfortunately, chomp() does not return the chomp()ed string, but a count of how many characters it removed, so you can't just say if(chomp(my $tmp = <CONF>)) and be done with it.)

Anyway, this is what I did:

open(CONF, "/var/web/onhit.conf");
chomp(my $tmp = <CONF>);
if($tmp) {
  print "Hello, world!\n";
}
close CONF;

A few recommendations:

  • Consider using the three-argument form of open(), or at least specifying "<" in front of the filename.
  • Consider using a variable to hold a filehandle ($conf) rather than using the older, clumsier filehandle form (CONF).

This is the code I would have written:

open my $conf, "<", "/var/web/onhit.conf";
chomp(my $tmp = <$conf>);
if($tmp) {
  print "Hello, world!\n";
}
close $conf;
Chris Lutz
Note the use of chomp() to remove the newline. Without it you would always execute the true branch regardless of the value.
Michael Carman
OK that works. Thanks. You forgot a parentheses on the first line though. And I actually said it wrong on my post. The if statement always evaluated. It's fixed now though.
Cory Walker
"You forgot a parentheses on the first line though." Woops. Fixed.
Chris Lutz
+1  A: 

You simply need to convert the string to an integer using the int function.

open(CONF, "/var/web/onhit.conf");
if(int(<CONF>)) {
    print "Hello World!";
}
close(CONF);
Jamie Cook
+1  A: 

Or you could just include in the newline in the comparison:

if (<CONF> =~ /^1$/) {
}
Chas. Owens
but what if they omitted the newline from the file? :)
ysth
@ysth Are you happy now?
Chas. Owens