“my $foo = $x if $y"有什么问题?句法? [英] What is wrong in "my $foo = $x if $y" syntax?
问题描述
在我在这里的最后一个问题中,@amon 给出了一个很好的答案.不过,他也说:
In my last question here, @amon gave an great answer. However, he told too:
首先,请不要做my $foo = $x if $y
.你出乎意料和未定义的行为,所以最好避免这种语法.
First of all, please don't do
my $foo = $x if $y
. You get unexpected and undefined behavior, so it is best to avoid that syntax.
因为我在 CPAN 的很多来源中看到了上述结构,我想知道它是如何、何时、哪里出错的.(一些示例代码会很好).也想知道,为什么 perl 允许它,如果它不好.
Because the above construction I was see in really many sources in the CPAN, I'm wondering how, when, where can be it wrong. (Some example code would be nice). Wondering too, why perl allows it, if it is bad.
推荐答案
他的措辞实际上有点松散.这句话其实是我的.让我们从文档开始:(强调原文)
His wording was actually a bit laxer. That wording is actually mine. Let's start with the documentation: (Emphasis in original)
注意:my
、state
或 our
的行为用语句修饰符conditional 或循环结构(例如,my $x if ...
)未定义.my
变量的值可以是 undef
、任何先前分配的值,或者可能是其他任何值.不要依赖它.未来版本的 perl 可能会做一些与您尝试使用的 perl 版本不同的事情.这里是龙.
NOTE: The behaviour of a
my
,state
, orour
modified with a statement modifier conditional or loop construct (for example,my $x if ...
) is undefined. The value of themy
variable may beundef
, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.
更准确地说,问题在于使用词法变量时其 my
可能尚未执行.
To be more precise, the problem is using a lexical variable when its my
may not have been executed.
考虑:
# Usage:
# f($x) # Store a value
# f() # Fetch and clear the stored value
sub f {
my $x if !@_;
if (@_) {
$x = $_[0];
} else {
return $x;
}
}
f('abc');
say "<", f(), ">" # abc
这显然不是 my
的记录行为.
This is obviously not the documented behaviour of my
.
因为我在 CPAN 的许多来源中都看到了上述结构
Because the above construction I was see in really many sources in the CPAN
那个代码有问题.
这篇关于“my $foo = $x if $y"有什么问题?句法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!