Programming and accessibility tips

from the Cynthia Network

Perl »

Generating array maps in Perl

The map function in Perl is a fast method for filling an array with values.

With the function syntax, map() takes two arguments and returns an array; the first argument is a function and the second argument is an array. @new_array = map(f, @array) iterates through the elements of @array. Each element during the iteration is stored in the variable $_. At each step in the iteration, the value returned from the function call f($_) is added to the output array @new_array. That is, @new_array is the array produced from passing the elements of @array to the function f.

Consider the following example:

my @array = ('this', 'is', 'an'. 'array');
my @lengths = map(length, @array);

In the code above, the array @lengths receives the value (4,2,2,5).

The map function can also be called using the block syntax. Using a code block instead of a function to produce the values in the output array allows for placing evaluation code directly into the map call without defining a function. The above code can be rewritten as follows:

my @array = ('this', 'is', 'an'. 'array');
my @lengths = map { length($_) } @array;

In the second program, map iterates through the values of @array, assigning each value to $_ which is used as the input to the call to length(). The output is placed in the @lengths array.

The following code produces an array containing powers of 2 using the elements of an input array as the exponents:

my @array = (1,2,3,4,5,6);
my @powers = { 2 ** $_ } @array;

In the above code, the array @powers receives the value (2,4,8,16,32,64).

Computer science help



By Bill Hollingsworth
© 2016 by Cynsight, LLC.
Cynthia™ is a trademark of Cynsight, LLC.