在我的最后一个问题中,@ amon给了
an great answer.但是,他也说过:
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允许它,如果它是坏的.
解决方法
他的措辞实际上有点松懈.这个措辞实际上是我的.让我们从
documentation开始:(重点是原创)
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.
更确切地说,问题是当我的可能没有被执行时使用词法变量.
考虑:
# 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
这显然不是我记录的行为.
Because the above construction I was see in really many sources in the CPAN
那个代码很麻烦.