in reply to "foreach" is to "next" as "map" is to ???

This is exactly what grep is for.

----
send money to your kernel via the boot loader.. This and more wisdom available from Markov Hardburn.

  • Comment on Re: "foreach" is to "next" as "map" is to ???

Replies are listed 'Best First'.
Re: Re: "foreach" is to "next" as "map" is to ???
by diotalevi (Canon) on May 26, 2004 at 16:29 UTC

    This is also what returning an empty list is for. grep is just a specialized form of map. Use map when you want to do other work as well.

    grep { TEST } map { TEST ? $_ : () }
      grep is just a specialized form of map

      Not entirely true.

      The difference between grep { TEST } and map { TEST ? $_ : () } is that grep returns a list of aliases to the elements that match TEST. map doesn't do this for obvious reasons - its return can be anything, it's in no way bound to $_.

      For example, if you have an array of numbers and you want to set any negative elements to zero, you can do it with the following code (of course this is not the most common way):

      $ perl @ary = (1, -5, -12, 7, 3); $_ = 0 for grep {$_ < 0} @ary; print "@ary\n"; ^D 1 0 0 7 3