views:

96

answers:

1
$ cat flaglist.log
flag1
flag2
flag3
flag4
$

Perl code

my $infile = "flaglist.log";
open my $fpi, '<', $infile or die "$!";
while (<$fpi>) {
    chomp;  
    if ($ENV{$_}) {   # something wrong here
        func($_);
    }       
    else {  
        print "oops\n";
    }       
}

$ perl code.pl
oops
oops
oops
oops
$

All the four flags are names of environment variables that are set (I checked using echo $flag1 from the shell).

Here the if condition always returns false. If I write $ENV{flag1}, it results to true and func() is called as I expected.

What am I doing wrong at the if statement?

+4  A: 

The code seems to work for me. Try stripping any whitespace from the input lines:

while (<$fpi>) {
    s/\s+//g;
    # ...
}
eugene y
@eugene, it works, but I don't understand. Wasn't chomp supposed to do the job?
Lazer
@Lazer: No. `chomp` only removes end of the string that corresponds to the value in `$/` which is `\n` by default. No other trimming takes place.
Alan Haggai Alavi
@Alan, yes, I know, but my file had no whitespace whatsoever except a newline, which was supposed to be removed by `chomp`.
Lazer
@Lazer - Are you sure? If you're on Unix, do "`cat -vet flaglist.log`" - see if there's a space between "1" and "$"
DVK
@DVK: Yes, there is a space. Thanks for pointing out, there is some problem in the code that generates `flaglist.log`.
Lazer
Also watch out for DOS style newlines on a Unix style system. It's common enough if your moving files between systems.
Ven'Tatsu
@Ven'Tatsu: `chomp` handles both EOL, contrary to `chop` which handles only one.
dolmen
@dolmen, `chomp` doesn't "handle both EOL", it removes the value in `$/` from the end of a string. On a Unix style systems `$/` contains by default `\x0a`. On DOS/Windows systems Perl's IO layers will by default translate `\x0d\x0a` to `\x0a` before the input is returned from the `readline` operator, unless the file is in `:raw` or a similar mode. This won't happen on other systems unless requested explicitly, resulting in a spare `\x0d` at the end of a line. `chop` doesn't handle any type of newlines, it just removes exactly one character from the end of a string.
Ven'Tatsu