in reply to Use grep with two arrays

my @keepers; foreach my $i (0..$#array1) { push @keepers, $i if $array1[$i] =~ /keep these/; } @array1 = @array1[@keepers]; @array2 = @array2[@keepers];

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^2: Use grep with two arrays
by revdiablo (Prior) on Feb 14, 2006 at 03:44 UTC

    Just for giggles, here's that using grep:

    my @keepers = grep { $array1[$_] =~ /keep these/ } 0 .. $#array1; @array1 = @array1[@keepers]; @array2 = @array2[@keepers];
      And to avoid the temp variable — not really a valid goal, but kind of fun — and not repeat the grep:
      my @a1 = qw'only keep ones that have es'; my @a2 = qw'art bart cart dart eart good'; @a1 = @a1[sort {$a <=> $b} grep {$a1[$_] =~ /e/ or do { splice @a2, $_ +, 1; 0 } } reverse 0..$#a1]; print "@a1\n@a2\n";
      It gets a little complicated, mostly because of the gyrations necessary to splice out the right element after others have been removed.

      Caution: Contents may have been coded under pressure.
      So to be inefficient and avoid the temp variable (untested):
      @array1 = @array1[+grep { $array1[$_] =~ /keep these/ } 0 .. $#array1 ]; @array2 = @array2[+grep { $array1[$_] =~ /keep these/ } 0 .. $#array1 ];

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

        Um, I think this suggestion, as you originally posted it, will not work as you intend/expect:
        @array1 = @array1[+grep { $array1[$_] =~ /keep these/ } 0 .. $#array1 ]; @array2 = @array2[+grep { $array1[$_] =~ /keep these/ } 0 .. $#array1 ];
        When you process @array2, @array1 is presumably shorter than it used to be -- the elements of the two arrays are no longer in parallel (assuming they were parallel before the first grep operation). You'll be getting the wrong elements left behind in @array2 (only the last elements of @array2 will ever be removed).

        And to then avoid reproducing code (which probably negates the advantages of not using a temp variable) (untested):

        @array1 = @array1[slicer(@array1)]; @array2 = @array2[slicer(@array1)]; sub slicer { grep { $_[$_] =~ /keep these/ } 0 .. $#_; }

            -Bryan