Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl foreach looping arrays, simple question

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.

like image 506
Sirex Avatar asked Jan 24 '26 06:01

Sirex


1 Answers

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.

like image 70
mscha Avatar answered Jan 26 '26 23:01

mscha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!