Top*_*der 7 variables perl if-statement
以下是什么问题.我收到了$attribute not defined错误.
if (my $attribute = $Data->{'is_new'} and $attribute eq 'Y') {
}
Run Code Online (Sandbox Code Playgroud)
bdo*_*lan 10
你太聪明了.这样做:
my $attribute = $Data->{'is_new'};
if (defined $attribute && $attribute eq 'Y') { ... }
Run Code Online (Sandbox Code Playgroud)
问题有两个:
)的ifmy在表达语境中绑定非常紧密; $attribute是不是在词法范围内,直到包含它的条件语句的主体,所以其他分支and无法访问它.您需要将其提升到包含上下文,如我的示例所示.ike*_*ami 10
use strict; 会发现问题.
$ perl -e'use strict; my $attribute = "..." and $attribute eq "Y";'
Global symbol "$attribute" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)
一个my声明只对后续语句的作用,而不是在其声明所在的语句.(同样适用于our和local声明.)这意味着$attribute您创建的my和您指定的变量是与$attribute您比较的变量不同的变量Y.你要
my $attribute = $Data->{'is_new'};
if ($attribute eq 'Y') { ... }
Run Code Online (Sandbox Code Playgroud)
现在,如果$Data->{is_new}不存在或未定义,$attribute将是未定义的,并且比较它将Y发出警告.您可以按如下方式避免此警告:
my $attribute = $Data->{'is_new'};
if (defined($attribute) && $attribute eq 'Y') { ... }
Run Code Online (Sandbox Code Playgroud)
或者:(5.10+)
my $attribute = $Data->{'is_new'};
if (($attribute // '') eq 'Y') { ... }
Run Code Online (Sandbox Code Playgroud)