Use map

G. Wade Johnson

Campbell Johnson

Perl's map operator

Fundamental operation on lists.

Similar in some ways to * for numbers

You can't really get good at list processing without using map. Looping instead of using map is sort of like doing repeated adds in a loop instead of using multiplication with integers.

What does it do?

Transform one list into another.

Keep this in mind every time you use map. If you are not really doing a transform, then map is the wrong tool.

Simple Example


   my @minutes = map { int( $_/60 ) } @seconds;

Simple transformation from an array of seconds into an array of minutes.

Better Example


  my @dts = map { DateTime->from_epoch( epoch => $_ ) }
            @unix_times;

The last example wasn't very likely to ever be really useful, but this is something that you might actually imagine doing. I have a list of Unix epoch times, but I want DateTime objects, so...

Weird Example

Turn the whole idea inside out: summary.pl.

I would never do this in production code, because the other developers would probably find it hard to follow. In this case, I'm processing a piece of data with an array of code references, to generate summary information about the data.