in reply to Re (tilly) 4: 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?

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

  • Comment on Re: Re (tilly) 4: How do I remove an element from any array while iterating over it in a loop?
  • Download Code

Replies are listed 'Best First'.
Re (tilly) 6: How do I remove an element from any array while iterating over it in a loop?
by tilly (Archbishop) on Aug 31, 2001 at 07:42 UTC
    I am perfectly aware of the fact that it is just a special case, the summary was not needed. However I am also aware from experience that people tend to look at you strangely when you have different numbers of return values in different cases. And furthermore the request was explicitly not a case of modifying elements, it was a straight filtering operation. Given that here are both strategies side by side if you assume that $unwanted is the element you are trying to remove:
    @filtered = map {$_ eq $unwanted ? () : $_} @original; @filtered = grep {$_ ne $unwanted} @original;
    Most people find the second much more readable. If you don't see why, then I suggest grabbing some co-workers, showing and explaining both, and trying to explain to them why they should find map more readable...

    Remember, generality often conflicts with readability. map is a far more general and complex function than grep. As such, when you see it you need to read very carefully, because a small detail can make a huge difference. But straight filtering is a very common need, and in that common case grep is simpler to write and easier to read.

      I am perfectly aware of the fact that it is just a special case, the summary was not needed I didn't intend to sound like I was talking down to you, if that's how it came across. And I'm sure you know the syntax...but lots of people are reading this thread, not just you and me.

      And furthermore the request was explicitly not a case of modifying elements, it was a straight filtering operation. Sorry, I missed that, typing replies while waiting on compiles. I thought he was doing a bunch of stuff with the element, and sometimes wanted to remove it as well. I guess he didn't need to be so complicated.

      Given that, I agree: to delete items that match a test, grep for the inverse of that test.

      —John