如何在strict pragma下将变量设置为NULL?

pow*_*boy 47 perl

use strict;
my $var = NULL;
Run Code Online (Sandbox Code Playgroud)

会引起错误 Bareword "NULL" not allowed while "strict subs" in use

Eug*_*ash 82

Perl中没有NULL.但是,变量可以被undef定义,这意味着它们没有设置值.
以下是一些如何在Perl中获取未定义变量的示例:

my $var;       # variables are undefined by default
undef $var;    # undef() undefines the value of a variable
$var = undef;  # same, using an alternative syntax
Run Code Online (Sandbox Code Playgroud)

要检查变量的定义,请使用defined(),即

print "\$var is undefined\n" unless defined $var;
Run Code Online (Sandbox Code Playgroud)

  • +1.和powerboy,在检查是否定义了什么时要小心.它是"if(定义$ var)"NOT"if(not undef $ var)".后者将取消定义$ var. (14认同)