12.4 Mapping
Like Common Lisp and similar languages, it is possible to map functions over a list in Perl. Mapping is introduced in Section 2.8. This means that we can take a function and execute the function with each element of the list taken as its actual parameter. For example, we may want to add 10 to every element of a list. The following function achieves that feat.
Program 12.8
#This subprogram is called with a list that contains one element
$add10 = sub {
my $number = $_[0];
$number + 10;
};
#calls &$add10 with every element of the list
@newlist = map {&$add10 ($_)} (1, 2, 3);
Here, we have defined an anonymous function which can be referenced using the scalar $add10. This function simply takes a parameter and adds 10 to it. The mapping of this function onto every element of a list can be performed using a call to the map function which is a built-in function in Perl. This function takes two parameters. The first parameter is a block of statements that operates on the special variable $_. The function is applied to each element of the list that is provided as the second parameter. As each element of the list is taken up for consideration, it is available to the mapped block as the value of the special variable $_. Here, the block passed as the first parameter to map calls
the anonymous function referenced by the scalar $add10. This function is called with the parameter $_. This function that operates on $_ is mapped on to the list containing three parameters: (1,2,3). So, at the end of the call, @newlist contains 11,12 and 13.