Transforming a Perl array using map

The map function of Perl provides a simple way to transform a
list of values to another list of values. Usually this is a one-to-one
transformation but in general the resulting list can be also shorter or
longer than the original list.

We saw that grep of Perl is a generalization of the
UNIX grep command. It selects some or all of the elements from the
original list, and returns them unchanged.

map, on the other hand, is used when you would like to make changes
to the values of the original list.

The syntax is similar. You provide a block of code and a list of values: an array
or some other expression that returns a list of values.
For every value in the original list, the value is placed in $_,
the default variable of Perl, and the block
is executed. The resulting values are passed on, to the left-hand side of the assignment.

map for simple transformation

Building fast look-up table

Sometimes we have a list of values and during the execution of the code
we need to check if a given value is within this list. We can use
grep every time, to check if the current
value is in the list. We can even use the any
function from List::MoreUtils,
but it can be much more readable and faster if we used a hash for lookup.

We need to create a hash once, where the keys are the elements of the array,
and the values of the hash are all 1s. Then, a simple hash lookup
can replace the grep.

Fat arrow

In case you are wondering => is called the fat arrow or fat comma. It basically acts
as a regular comma , with an exception that is not relevant in our case. (There is a description
of it in the article about Perl hashes.)