尝试在 perl 中的 oneline 中编写 foreach 并失败

发布于 2024-11-04 00:54:26 字数 266 浏览 5 评论 0原文

Perl 新手,尝试稍微尝试一下它的语法,然后我收到以下错误消息

$ perl testP
syntax error at testP line 3, near "$_ ("
Execution of testP aborted due to compilation errors.

$_=$_+1 foreach $_ (@_);

谁能告诉我出了什么问题以及如何修复它?谢谢。

new to perl, trying to playing around with its syntax a bit, then I got this error message

$ perl testP
syntax error at testP line 3, near "$_ ("
Execution of testP aborted due to compilation errors.

for:

$_=$_+1 foreach $_ (@_);

Can anyone tell me what went wrong and how to fix it? thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

川水往事 2024-11-11 00:54:27

foreach 变量( array )以正常表示法使用,例如:

foreach $_ ( @_ ) {
    $_ = $_ + 1;
}

但您使用了相反的表示法,即先操作,然后循环。

在这种情况下,您无法为循环提供变量名称(无论如何,这都是无用的,因为您使用的是默认变量 $_),并且循环应该如下所示:

$_ = $_ + 1 foreach @_;

另请注意,您可以使用 for 代替foreach,如果你只是想增加变量,你可以使用 ++ 运算符来实现,从而使其:

$_++ for @_;

foreach variable ( array ) is used in normal notation like:

foreach $_ ( @_ ) {
    $_ = $_ + 1;
}

But you used the reverse notation, that is operation first, and loop then.

In this case you cannot provide variable name for the loop (which is useless anyway, since you're using default variable $_), and the loop should look:

$_ = $_ + 1 foreach @_;

Please also note that you can use for instead of foreach, and if you simply want to increment variable, you can do it with ++ operator, thus making it to:

$_++ for @_;
狂之美人 2024-11-11 00:54:27

$_ 将在 foreach每次迭代中获得 @_每个不同值>,并且 ++ 运算符将对值进行后递增。

所以像这样的东西会起作用:

foreach (@_) {$_++;}

注意: $_++ 相当于 $_ = $_ + 1

$_@_ 是 perl 中的特殊变量,它们有特殊的行为,在这种情况下,foreach 循环上下文中的 $_ 会获取每个变量的当前值迭代。

特殊变量是 Perl 中复杂而强大的部分之一。您可以在特殊变量文档中获取有关它们如何工作的更多信息。

另一件事是您不应该使用特殊变量作为foreach的目标,因为它们很可能无法按预期工作(另请参阅foreach 文档

$_ will get each different value of @_ on each iteration of the foreach, and the ++ operator will postincrement the values.

So something like this will work:

foreach (@_) {$_++;}

Note: $_++ is equivalent to $_ = $_ + 1

$_ and @_ are special variables in perl and they have an special behavior, in this case $_ in the context of a foreach loop takes the current value on each iteration.

Special variables are one of the complex and powerful parts of perl. You can get some more information about how they work on the special vars documentation.

Another thing is you shouldn't use a special variable as target of the foreach as they most probably won't work as expected (see also the foreach documentation)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文