9.2. map
The map function traverses an array and maps each element to one or more ( or zero) elements in a new array. It has a rather unorthodox syntax in that it is written as @new_array = (map { <Some Expression with $_> } @array) .
For each element of the array @array, the variable $_ is assigned its value, and within the curly brackets one can put an expression that is dependant on it.
The following example multiplies each element of an array by two:
use strict; use warnings; my @array = (20, 3, 1, 9, 100, 88, 75); my @new_array = (map { $_*2; } @array); print join(",", @new_array), "\n";
Using map is usually faster than using a foreach $elem (@array) { ... push @new_array, $new_elem; } loop, at least when the function performed is a relatively uncomplex one.
The following program decodes a run-length encoding compression, in which each element of the array is a number followed by its number of times:
use strict; use warnings; my $default_input_string = "2-5,3-9,1-2,8-1,4-7,5-9,20-3,16-9"; my $input_string = shift || $default_input_string; # RLE stands for Run-Length Encoding my @rle_components = split(/,/, $input_string); my @expanded_sequence = (map { my ($what, $times) = split(/-/, $_); (($what) x $times); } @rle_components ); print join(",", @expanded_sequence), "\n";
As you can see, the expression at the end of the map iterator can be an array with more than one element. It can also be an empty array, which means that some elements can be filtered out.