http://qs1969.pair.com?node_id=501419

jfroebe has asked for the wisdom of the Perl Monks concerning the following question:

I've been reading a book on DBMS administration using perl (specific book doesn't matter) and have seen this in other perl books as well. (I'm not singling out any author)

Several books tend to avoid the use of map and grep. I can only assume that the authors have trouble explaining the usage and benefits of these in such a way that perl programmers can understand. How can we explain map and grep better?

One of the benefits is that often, using map or grep provides increased performance (see example below). Another is that you can chain the greps and maps together to make your life so much easier.

I'm convinced that map & grep aren't as heavily used as they could be because people don't understand them.

Example:

#!/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); ## benchmark to determine best method ## of finding common elements in two ## arrays my @array1 = ( '0', '1', '2', '3', '5' ); my @array2 = ( '0', '1', '2', '3', '4', '6' ); cmpthese (100000, { 'using foreach' => sub { my @common; foreach my $element1 (@array1) { foreach my $element2 (@array2) { if ($element1 eq $element2) { push @common, $element1 unless grep { $element +1 eq $_ } @common; } } } }, 'using grep' => sub { my @common; @common = grep { my $element1 = $_; ! grep { $element1 == $_ } @array2 } @array2; } });

Benchmark:

$ ./test_bm_array Rate using foreach using grep using foreach 6873/s -- -30% using grep 9766/s 42% --

Jason L. Froebe

Team Sybase member

No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1