Perl foreach loop arrays, simple question

A really simple question, but it really bothers me.

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

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

What I need to do to do the second job (i.e. assign an array separately), I used the first form as a fair bit, but I donโ€™t understand what it does differently.

+3
source share
1 answer

Maybe:

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

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

In addition, you must really use strict;and use warnings;, and declare your variables as

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

(, , ), script.

+8

Source: https://habr.com/ru/post/1774276/


All Articles