开发者

perl foreach looping arrays, simple question

开发者 https://www.devze.com 2023-01-24 07:20 出处:网络
Really simple perl question, but confusing me greatly. foreach $val (@{$obj->something()}) { # this works

Really simple perl question, but confusing me greatly.

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

@array = $obj->something();
foreach $val (@array) {
    #开发者_C百科 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消