Categories
Software and Programming

Perl: map vs. grep

Stuff worth reading:

Tutorial about Perl’s map, grep and sort functions by RayCosoft.

an article about the map function by Simon Cozens, tracing its origins to Lisp.

The list manipulation functions are also covered in Idiomatic Perl, an excellent presentation by Dave Cross about writing better Perl. Required reading.

Effective Perl Programming:
Without a map You Can Only grep
Your Way Around
: The map operator is more versatile and can do anything that grep can:… (he demonstrates).

Both grep and map work on whole lists, and take an expression or block as an argument. A grep filters the list, returning only the values for which the block evaluated as true; the map applies the block to each value in the list and returns the result(s). The trick I was looking for (how to both transform and filter a list) requires that the block should return nothing if a condition isn’t met. The way to do it appears to be to explicitly return an empty list (the default return value counts as something for the purpose of filling the results list).

Lists are cool. Most popular languages take after C in focusing on arrays and leaving lists as second-class citizens, but Perl (and I guess Lisp, Python, Ruby, whatever) let you do operations on whole lists, which lets you think at a higher-level of abstraction.

Other cool Perl stuff I ran across is this article proposing to show Seven Useful Uses of local.