perlenvironment-variablesperl-io

How do I access environment variables correctly in Perl?


Consider:

cat flaglist.log

Output:

flag1
flag2
flag3
flag4

Perl code

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

Run:

perl code.pl

Output:

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?


Solution

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

    while (<$fpi>) {
        s/\s+//g;
        # ...
    }