当前位置: 动力学知识库 > 问答 > 编程问答 >

How do I access environment variables correctly in Perl?

问题描述:

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

网友答案:

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

while (<$fpi>) {
    s/\s+//g;
    # ...
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: