English 中文(简体)
我的 Perl 程序为什么会警告未初始化的值?
原标题:Why does my Perl program warn about an uninitialized value?

我写了下面的Perl脚本,它生成了一个警告,但我无法弄清楚为什么。

#!/usr/local/bin/perl -w

$status = $ENV{  STATUS  };
if ( $status eq "" )
{
    $status = 0;
}
else
{
    $status = 1;
}

它说"在./x.pl线4: 字符串eq中使用未初始化的值。"

第四行是“if ($status eq "")”的行,但变量已经初始化了...

我该如何摆脱这个警告?

最佳回答

$ENV{ STATUS } 可能未定义。

如果你跑步

export STATUS=blah

在运行Perl脚本之前,在Shell中运行,它会起作用。

修复它

#!/usr/local/bin/perl -w
$status = $ENV{  STATUS  };
if (!defined($status) || $status eq "" )
{
    $status = 0;
}
else
{
    $status = 1;
}
问题回答

另一个选择是

$status = $ENV{  STATUS  } //   ;

如果未定义,它将把$status设置为空字符串,但是//运算符只存在于Perl 5.10及更高版本中。与之等效的5.10之前的语法是。

$status = defined $ENV{STATUS} ? $ENV{STATUS} :   ;

尽管很多人会假装。

$status = $ENV{  STATUS  } ||   ;

但是这会将 $ENV{STATUS} 的值从0更改为一个空字符串,这可能会对您造成影响或不造成影响。

这些都是通用的答案。然而,在你发布的特定代码中,将其全部替换为

$status = defined $ENV{STATUS} ? 1 : 0;

简单 (jiǎn dān)

$status = defined $ENV{STATUS};

(如果你把没有固定价值的东西改成空洞而不是0)是更好的选择。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签