Search code examples
perlreturnelementsubroutine

perl return all elements in array individually from subroutine


total perl noob here.

I'm trying to write a program that will:

  1. process several groups of words (one array=one group) in a subroutine
  2. return the results to one gigantic array
  3. modify the gigantic array later in the program

Currently, my gigantic array is an array of arrays, and it's a hassle to work with. Is there any way I can return the results as individual elements, instead of an array reference? The smaller arrays are of variable lengths.

So say after processing my array results are this:

@array=["A", "B", "C", "D"];

I'd like:

@giganticarray=["array1stuff", "etc", "A", "B", "C", "D", "array3stuff", "etc"];

I tried this:

foreach (@array){
        return $_;
}

and this

for (my $n=scalar (@array); $n>0; $n--) {
        return $array[$n];
}

I can't find any information on the web, but it may be because I'm looking for the wrong thing. I'd appreciate any help.


Solution

  • To flatten an array of arrays, you need just

    @giganticarray = map { ref $_ ? @$_ : $_ } @giganticarray
    

    but it would be much cleaner if you generated the array the way you want it in the first place. Show us your code and we can show you how