0
$ 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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Lazer
  • 90,700
  • 113
  • 281
  • 364
  • 2
    You may mean `if( exists $ENV{$_} )`. Your current test will fail if you have an environment variable set to `0`. – daotoad Sep 30 '10 at 19:37

1 Answers1

4

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

while (<$fpi>) {
    s/\s+//g;
    # ...
}
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • @eugene, it works, but I don't understand. Wasn't chomp supposed to do the job? – Lazer Sep 30 '10 at 11:28
  • 5
    @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 Sep 30 '10 at 11:32
  • @Alan, yes, I know, but my file had no whitespace whatsoever except a newline, which was supposed to be removed by `chomp`. – Lazer Sep 30 '10 at 11:38
  • 5
    @Lazer - Are you sure? If you're on Unix, do "`cat -vet flaglist.log`" - see if there's a space between "1" and "$" – DVK Sep 30 '10 at 11:44
  • 1
    @DVK: Yes, there is a space. Thanks for pointing out, there is some problem in the code that generates `flaglist.log`. – Lazer Sep 30 '10 at 12:04
  • 1
    Also watch out for DOS style newlines on a Unix style system. It's common enough if your moving files between systems. – Ven'Tatsu Sep 30 '10 at 14:04
  • @Ven'Tatsu: `chomp` handles both EOL, contrary to `chop` which handles only one. – dolmen Oct 01 '10 at 17:07
  • @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 Oct 07 '10 at 15:39