如何检查变量是否在perl中声明?

Shu*_*ham 8 perl

use strict;在perl中使用,并使用以下语句.

unless(defined($x)){
      print "Not defined";
}
Run Code Online (Sandbox Code Playgroud)

其中$ x未在任何地方声明.所以我希望它打印" Not defined"但它会返回一个错误

Global symbol "$x" requires explicit package name at *********** in line 15.
Run Code Online (Sandbox Code Playgroud)

Gre*_*con 18

strictpragma有三个部分:严格引用,严格变量和严格的subs.你遇到的那个是

严格的变种

This generates a compile-time error if you access a variable that wasn't declared via our or use vars, localized via my, or wasn't fully qualified. Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely local variable isn't good enough.

Because it generates compile-time errors, your non-BEGIN code won't even have a chance to run. You can temporarily allow non-strict variables inside a block as in

{
  no strict 'vars';
  print "Not defined!\n" unless defined $x;
}
Run Code Online (Sandbox Code Playgroud)

but note that Perl's defined operator tells you whether a value is defined, not whether a variable has been declared.

Tell us more about your application, and we can give you better advice about how to handle it.

  • 重要的部分是未声明和未定义之间的区别。 (2认同)

Axe*_*man 5

除非声明变量,否则甚至无法引用变量.当你问

defined( $x ) ?
Run Code Online (Sandbox Code Playgroud)

编译器会抱怨:我不知道你问的是什么,我该如何判断它的定义?它没有该变量的参考点,因为您已经表明您不希望通过名称自动创建变量.

如果strict 'vars'没有打开 - 默认情况下是 - 那么use strict它会在包符号表中为'x'创建一个条目.

有趣的是,没有strict 'refs'它也很容易检查变量是否在包符号表中.

defined( *{ __PACKAGE__ . '::x' }{SCALAR} )
Run Code Online (Sandbox Code Playgroud)

由于无法自动创建词法("我的变量"),因此也没有标准方法来检查是否声明了词法.词汇变量存储在"pad"中.但是有一个模块PadWalker可以提供帮助.

为了检查当前级别,您可以获得填充的哈希,然后检查它是否存在于当前填充中.您也可以通过堆栈循环(整数参数的工作方式类似caller)来查找最近的x所在的位置.

my $h = peek_my (0);
exists $h->{x};
Run Code Online (Sandbox Code Playgroud)


Pab*_*cia 5

我认为你正在混合'定义'和'声明'的概念.

您要求'如何检查变量是否在perl中声明',但是您正在检查是否定义了变量.这是两个不同的概念.

在perl中,如果使用'use strict',则会自动检查未声明的任何变量(使用my,localour).一旦声明了变量,就可以测试它是否已定义(分配了值).

因此,在测试中,在测试defineness之前,您缺少先前的声明

use strict;
my $x;  # you are missing this part
[...] | # code
# your test for define
print defined $x? "defined\n" : "not defined\n";
Run Code Online (Sandbox Code Playgroud)

请注意,只有$ x的测试不符合您的目的:

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
Run Code Online (Sandbox Code Playgroud)

最后,xenorraticide的答案似乎对我来说是错误的:他建议'除非$ x',如果按照我之前的说法进行定义,则测试不正确.他还建议'除非存在$ x',这对于测试标量是错误的.'exists'测试仅适用于散列键(并且不适用于数组).

希望这可以帮助.