这个 Perl 表达式有什么问题?
下面有什么问题。我收到 $attribute not Defined
错误。
if (my $attribute = $Data->{'is_new'} and $attribute eq 'Y') {
}
What's the problem with following. I am getting $attribute not defined
error.
if (my $attribute = $Data->{'is_new'} and $attribute eq 'Y') {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你太聪明了。只需这样做:
问题是双重的:
my
中,您有一个额外的)
$attribute
直到包含它的条件语句主体才处于词法范围内,因此and
的另一个分支无法访问它。您需要将其提升到包含上下文,如我的示例所示。You're being too clever. Just do this:
The problems are twofold:
)
in your ifmy
in expression context binds very tightly;$attribute
is not in lexical scope until the body of the conditional statement that contains it, so the other branch of theand
cannot access it. You need to lift it to the containing context, as in my example.use strict;
就会发现问题。my
声明仅对后续语句产生影响,而不会影响该声明所在的语句。 (our
和local
声明也是如此。)这意味着您使用my
创建的$attribute
和您指定的变量与您与Y
进行比较的$attribute
不同。现在,如果
$Data->{is_new}
不存在或未定义,则$attribute
将未定义,并将其与Y< /code> 将发出警告。您可以按如下方式避免此警告:
或者:(5.10+)
use strict;
would have found the problem.A
my
declaration only has an effect on subsequent statements, not the the statement in which the declaration is is located. (Same goes for theour
andlocal
declarations.) That means the$attribute
that you create withmy
and to which you assign is a different variable than the$attribute
you compare toY
. You wantNow, if
$Data->{is_new}
doesn't exist or is undefined,$attribute
will be undefined, and comparing it toY
will issue a warning. You can avoid this warning as follows:Alternatively: (5.10+)
其他答案都很好。我只是想补充一点,如果您想避免使用
$attribute
变量混淆周围的范围,您可以这样做:这也适用于
strict
和warnings.
The other answers are good. I just want to add that if you want to avoid cluttering the surrounding scope with the
$attribute
variable you could do:This also works with
strict
andwarnings
.正如已经提到的,您不能在声明变量的同时使用它。事情就是这样;您需要先完成声明语句,然后才能使用新变量。
不过,坦率地说,我有点迷失,为什么还没有提到这一点,你本来可以做的是:
$attribute
尚未声明,但是$Data->{'is_new'}
是。需要明确的是:这个 if 语句的要点是三件事:
$attribute
分配一个值$attribute
的词法范围是 if 语句后续块的内部,不多也不少。Like has already been mentioned, you cannot declare a variable and use it at the same time. That's just the way it is; You need to finish the declaration statement before you can use the new variable.
What you could have done though, and I am frankly somewhat lost as to why this has not been mentioned yet, is this:
$attribute
is not yet declared, but$Data->{'is_new'}
is.Just to be clear: The point of this if statement would then be three things:
$attribute
'Y'
The lexical scope of
$attribute
is the inside of the if-statements subsequent block, no more, no less.