map
mapBLOCKLISTmapEXPR,LIST
This function evaluates the BLOCK or
EXPR for each element of
LIST (locally setting $_ to each element) and returns the list
comprising the results of each such evaluation. It evaluates
BLOCK or EXPR in
list context, so each element of LIST may map
to zero, one, or more elements in the returned value. These are all
flattened into one list. For instance:
@words = map { split " " } @lines;splits a list of lines into a list of words. But often there is a one-to-one mapping between input values and output values:
@chars = map chr, @nums;
translates a list of numbers to the corresponding characters. And here’s an example of a one-to-two mapping:
%hash = map { genkey($_) => $_ } @array;which is just a funny functional way to write this:
%hash = ();
for my $_ (@array) {
$hash{genkey($_)} = $_;
}Because $_ is an alias
(implicit reference) into the list’s values, this variable can be used
to modify the elements of the array. This is useful and supported,
although it can cause bizarre results if the
LIST is not a named array. Using a regular
foreach loop for this purpose may be
clearer. See also grep; map differs from grep in that map returns a list consisting of the results
of each successive evaluation of EXPR,
whereas grep returns a list
consisting of each value of LIST for which
EXPR evaluates to true.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access