Idiomatic Perl and Map

map, in perl, runs a specific piece of code once for each element in a list. The result of each iteration (in list mode; each iteration can return a list of any size from zero to the limits of the machine) is turned into a single list, which is the result of the map command. Within the map, $_ refers to the current element being worked on.

Map is a function can run on either a single expression or a block, as follows:

@result = map { BLOCK } @list;


@result = map $expression, @list;

Some notes:

',' and '=>' are near synonyms in perl. Because of this, '=>' is often used instead of ',' to differentiate the operand in the list (the first argument) from any other operators.

@list can be any list -- "@result = map $_+1 => 1,2,3,4;" will result in (2,3,4,5).

Because it is more elegant to do only what's necessary, and because there is a noticable (but very small) performance penalty for using a block rather than an expression, experienced perl programmers may use an expression for somewhat more complex versions of map. There are a few tricks sometimes employed in this -- most notably that while a parenthesis right after a function name will be treated as the function parenthesis, putting a + there instead won't change the result but will cause the parenthesis to be treated as a normal parenthesis (one can just use function parenthesis with the parenthetical block inside instead; this looks much nicer).

my ($one,$two,$three,$cantelope,@list) = (1..3,"cantelope",9..12);
#the following two lines are identical:
@result = map +(/cantelope/ ? "orange" : $_+1) => $one,$two,$three,$cantelope, @list;
@result = map ((/cantelope/ ? "orange" : $_+1), $one,$two,$three,$cantelope,@list);