Perl FAQ 4.36: What's wrong with grep() or map() in a void context?

Perl FAQ 4.36

What's wrong with grep() or map() in a void context?

Well, nothing precisely, but it's not a good way to write maintainable code. It's just fine to use grep when you want an answer, like

    @bignums = grep ($_ > 100, @allnums);
    @triplist = map {$_ * 3} @allnums;

But using it in a void context like this:

    grep{ $_ *= 3, @nums);

Is using it for its side-effects, and side-effects can be mystifying. There's no void grep that's not better written as a for() loop:

    for (@nums) { $_ *= 3 } 

In the same way, a ?: in a void context is considered poor form:

    fork ? wait : exec $prog;

When you can write it this way:

    if (fork) {
	wait;
    } else {
	exec $prog;
	die "can't exec $prog: $!";
    } 

    

Of course, using ?: in expressions is just what it's made for, and just fine (but try not to nest them.).

Remember that the most important things in almost any program are, and in this order:

  1. correctness
  2. maintainability
  3. efficiency
Notice at no point did cleverness enter the picture.

On the other hand, if you're just trying write JAPHs (aka Obfuscated Perl entries), or write ugly code, you would probably invert these :-)

  1. cleverness
  2. efficiency
  3. maintainability
  4. correctness