in reply to Re: How do I remove an element from any array while iterating over it in a loop?
in thread How do I remove an element from any array while iterating over it in a loop?

<cough> grep </cough>
   MeowChow                                   
               s aamecha.s a..a\u$&owag.print
  • Comment on (MeowChow) Re2: How do I remove an element from any array while iterating over it in a loop?
  • Select or Download Code

Replies are listed 'Best First'.
Re: (MeowChow) Re2: How do I remove an element from any array while iterating over it in a loop?
by John M. Dlugosz (Monsignor) on Aug 30, 2001 at 23:04 UTC
    Hmm, using grep, your "test" is the iteration code and returns true to keep, false to discard. Cute. Maybe too cute to understand later, though?

      Using map when grep would do takes more code and an easy to miss trick with returning empty lists. Plus saying map gives no indication of why you have the operation. Saying grep gives a strong indication of filtering to anyone who has been near Unix or who has read perlfunc.

      Therefore I would say that using map and tricky return lists is significantly less maintainable than using grep where grep would fit.

        I guess I didn't really consider returning an empty list a "trick" with map. I know I can return multiple elements, that whatever I return is raveled up into the output list, and zero is just a case of that.

        Here's the summary:

        @array= map { map_proc } @array; @array= grep { map_proc } @array;
        where grep_proc returns true (keep) or false (discard); and map_proc returns the original element to keep, or an empty list to discard.

        I agree that grep gives the idea of filtering. But he's not just filtering; he's altering. Altering where "delete" is one possibility.

        —John