3

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.