perl foreach循环数组,简单的问题

发布于 2024-10-01 23:33:31 字数 244 浏览 0 评论 0原文

非常简单的 Perl 问题,但让我很困惑。

foreach $val (@{$obj->something()}) {
    # this works
}

@array = $obj->something();
foreach $val (@array) {
    # this does not
}

我需要做什么才能完成第二项工作(即:单独分配数组),我已经使用了相当多的第一种形式,但并不真正理解它的不同之处。

Really simple perl question, but confusing me greatly.

foreach $val (@{$obj->something()}) {
    # this works
}

@array = $obj->something();
foreach $val (@array) {
    # this does not
}

What do i need to do to make the second work (i.e: assign the array seperately), i've used the first form a fair bit but dont really understand what it does differently.

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

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

发布评论

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

评论(1

独闯女儿国 2024-10-08 23:33:31

可能:

@array = @{$obj->something()};

从第一个示例中,看起来 $obj->something() 返回一个数组引用,您需要取消引用它。

另外,您确实应该use strict;use warnings;,并像这样声明您的变量,

my @array = @{$obj->something()};
foreach my $val (@array) {
    # this does not
}

这将使您更容易发现错误(尽管可能不是这个),即使在三行脚本中。

Probably:

@array = @{$obj->something()};

From the first example, it looks like $obj->something() returns an array reference, you'll need to dereference it.

Also, you should really use strict; and use warnings;, and declare your variables like

my @array = @{$obj->something()};
foreach my $val (@array) {
    # this does not
}

This will make it much easier to find mistakes (although probably not this one), even in a three line script.

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