我在使用Perl中的use strict;
,并且我使用以下语句。
unless(defined($x)){
print "Not defined";
}
变量$x没有被声明。所以我期望它打印出 "Not defined
" 但是它返回了一个错误。
Global symbol "$x" requires explicit package name at *********** in line 15.
我在使用Perl中的use strict;
,并且我使用以下语句。
unless(defined($x)){
print "Not defined";
}
变量$x没有被声明。所以我期望它打印出 "Not defined
" 但是它返回了一个错误。
Global symbol "$x" requires explicit package name at *********** in line 15.
strict
严格语法检查模块有三个部分:严格引用、严格变量和严格子程序。你遇到的是:
strict vars 严格变量
如果访问了一个没有通过
our
或use vars
声明,或者没有被通过my
局部化,或者没有被完全限定的变量,这将生成一个编译时错误。因为这是为了防止变量自杀问题和微妙的动态作用域问题,所以仅仅使用local
变量是不够的。
由于它会生成编译时错误,因此您的非 BEGIN
代码甚至没有机会运行。您可以在代码块内暂时允许非严格变量,如下所示:
{
no strict 'vars';
print "Not defined!\n" unless defined $x;
}
但请注意,Perl的defined
运算符告诉您一个值是否被定义,而不是一个变量是否已经声明。
告诉我们更多关于你的应用程序,我们可以给你更好的建议来处理它。
defined( $x ) ?
strict 'vars'
(默认情况下使用use strict
),则会为“x”在包符号表中创建一个条目。strict 'refs'
,也很容易检查变量是否在包符号表中。defined( *{ __PACKAGE__ . '::x' }{SCALAR} )
PadWalker
的模块可以帮助解决这个问题。caller
),以找到最近的x所在位置。my $h = peek_my (0);
exists $h->{x};
use strict;
my $x; # you are missing this part
[...] | # code
# your test for define
print defined $x? "defined\n" : "not defined\n";
my ($x,$y, $z);
$w; # not declared (use strict will catch it and die)
$x = 0; # declared and defined BUT if you make a logic test like 'if ($x) {}' then it will be FALSE, so don't confuse testing for **'$x'** and testing for **'defined $x'**
$y = undef; # declared but not defined
$z = 1; # declared, defined, and logial test TRUE
通常这种代码不应该在一个严肃的程序中使用,但为什么不只是为了好玩呢:(假设使用严格模式)
print "Not defined\n" unless eval 'ref(\$x)';
#
print "Not defined" if !defined($x);
结果将会是
未定义
#
use strict;
print "Not defined" if !defined($x);
将会生成与您的问题类似的错误。
请查看:http://perldoc.perl.org/strict.html,其中描述了如何仅导入所需的限制。(但使用 strict 'vars' 是一个非常好的想法 :))
似乎可以通过以下方式检查变量是否已声明(如 man perlmod
中的“符号表”部分所述):
main::(-e:1): 1
DB<1> x __PACKAGE__
0 'main'
DB<2> x exists ${__PACKAGE__ . '::'}{xyz}
0 ''
DB<3> $xyz = undef
DB<4> x exists ${__PACKAGE__ . '::'}{xyz}
0 1
DB<5> $xyz = 7
DB<6> x exists ${__PACKAGE__ . '::'}{xyz}
0 1
perl -d -e 1
后,你会进入包 main
,其中 $xyz
没有被声明。
因此 ("全局") xyz
在 main
的符号表中不存在。
但是,将 undef
赋值给该名称的变量后,符号表中就会有一个条目。my
变量(词法作用域)不起作用。#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;