The map() function

The map() function can be used to perform an action on each member of a list and return the results as a list.

my @lowercase = map lc, @words;
my @doubled = map { $_ * 2 } @numbers;

map() is often a quicker way to achieve what would otherwise be done by iterating through the list with foreach.

foreach (@words) {
        push (@lowercase, lc($_);
}

Like grep(), it doesn't require a comma between its arguments if you are using a block as the first argument, but does require one if you're just using an expression.

Exercises

  1. Create an array of numbers. Use map() to find the square of each number. Print out the results.