如何检查变量是否在perl中声明? [英] How to check if variable is declared in perl?

查看:39
本文介绍了如何检查变量是否在perl中声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using use strict; in perl and with that I use the following statement.

unless(defined($x)){
      print "Not defined";
}

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

Where $x is not declared anywhere. So I expect it to print "Not defined" but it returns an error

Global symbol "$x" requires explicit package name at *********** in line 15.

推荐答案

strict pragma 包含三部分:严格引用、严格变量和严格子项.你遇到的是

The strict pragma has three parts: strict references, strict variables, and strict subs. The one you're running into is

如果您访问的变量不是通过 ouruse vars 声明的,而是通过 my 本地化的,则会生成编译时错误,或者不完全合格.因为这是为了避免变量自杀问题和微妙的动态范围问题,仅仅使用 local 变量是不够的.

strict vars

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.

因为它会生成编译时错误,所以您的非BEGIN 代码甚至没有机会运行.您可以在块中临时允许非严格变量,如

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;
}

但请注意,Perl 的 defined 运算符告诉您值是否已定义,而不是变量是否已声明.

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.

这篇关于如何检查变量是否在perl中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆