in reply to Re: Use grep with two arrays
in thread Use grep with two arrays

Just for giggles, here's that using grep:

my @keepers = grep { $array1[$_] =~ /keep these/ } 0 .. $#array1; @array1 = @array1[@keepers]; @array2 = @array2[@keepers];

Replies are listed 'Best First'.
Re^3: Use grep with two arrays
by Roy Johnson (Monsignor) on Feb 14, 2006 at 19:20 UTC
    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.
Re^3: Use grep with two arrays
by QM (Parson) on Feb 14, 2006 at 17:54 UTC
    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).
        Yes, of course. Put it's supposed to DWIM, even if I ask the impossible, right? ;)

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

      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