arraysperlblank-line

Perl: grep from multiple arrays at once


I have multiple arrays (~32). I want to remove all blank elements from them. How can it be done in a short way (may be via one foreach loop or 1-2 command lines)?

I tried the below, but it's not working:

    my @refreshArrayList=("@list1", "@list2", "@list3","@list4", "@list5", "@list6" , "@list7");
    foreach my $i (@refreshArrayList) {
        $i = grep (!/^\s*$/, $i);
    }

Let's say, @list1 = ("abc","def","","ghi"); @list2 = ("qwe","","rty","uy", "iop"), and similarly for other arrays. Now, I want to remove all blank elements from all the arrays.

Desired Output shall be: @list1 = ("abc","def","ghi"); @list2 = ("qwe","rty","uy", "iop") ### All blank elements are removed from all the arrays.

How can it be done?


Solution

  • You can create a list of list references and then iterator over these, like

    for my $list (\@list1, \@list2, \@list3) {
         @$list = grep (!/^\s*$/, @$list);
    }
    

    Of course, you could create this list of list references also dynamically, i.e.

    my @list_of_lists;
    push @list_of_lists, \@list1;
    push @list_of_lists, \@list2;
    ...
    for my $list (@list_of_lists) {
         @$list = grep (!/^\s*$/, @$list);
    }