gpt4 book ai didi

perl - "my $foo = $x if $y"语法有什么问题?

转载 作者:行者123 更新时间:2023-12-04 06:38:54 26 4
gpt4 key购买 nike

在我最后一个问题中,@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, or our modified with a statement modifier conditional or loop construct (for example, my $x if ...) is undefined. The value of the my variable may be undef, 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可能没有被执行。

考虑:
# 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 的记录行为。 .

Because the above construction I was see in really many sources in the CPAN



那个代码有问题。

关于perl - "my $foo = $x if $y"语法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com