ZetCode

Perl map

last modified November 25, 2026 Perl 5.44

The Perl map function evaluates a block or an expression for each element of a list and returns the list of results. It transforms one list into another without an explicit loop.

Inside the block, the current element is available in $_. The block is evaluated in list context, so it may return one value, several values or none at all for each element. To select elements without changing them, see Perl grep.

A basic map example

The first example doubles every number of an array and collects the results in a new array.

basic.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @numbers = (2, 4, 6, 8);
my @doubled = map { $_ * 2 } @numbers;

say "@doubled";
say "@numbers";

The block { $_ * 2 } runs once for each element of @numbers, and the value of its last expression is added to the output list. The original array is left unchanged.

$ perl basic.pl
4 8 12 16
2 4 6 8

The expression form

map has two forms: map BLOCK LIST and map EXPR, LIST. The expression form needs a comma after the expression; the block form must not have one.

expr_form.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @words = qw(sky ocean forest);

my @upper = map { uc } @words;
my @lengths = map length, @words;
my @tagged = map "<$_>", @words;

say "@upper";
say "@lengths";
say "@tagged";

Many built-in functions use $_ when called without an argument, so map { uc } @words and map length, @words need no explicit variable. The last line interpolates $_ in a double-quoted string. The block form is more common, because it accepts several statements and is easier to read.

$ perl expr_form.pl
SKY OCEAN FOREST
3 5 6
<sky> <ocean> <forest>

Formatting values

A frequent use of map is to turn raw values into display strings. The sprintf function fits well inside the block.

format.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @prices = (3, 12.5, 0.99, 140);

my @formatted = map { sprintf '%8.2f EUR', $_ } @prices;
say for @formatted;

my @with_vat = map { $_ * 1.2 } @prices;
say join ', ', map { sprintf '%.2f', $_ } @with_vat;

The first map formats each price in a column eight characters wide with two decimal places. In the second part, one map computes the prices with tax and another formats them. The result of the inner call is passed directly to join.

$ perl format.pl
    3.00 EUR
   12.50 EUR
    0.99 EUR
  140.00 EUR
3.60, 15.00, 1.19, 168.00

Returning several values

The output list does not need to have the same length as the input list. When the block returns a list, all its elements are added to the result.

several.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @lines = ('an old falcon', 'a blue sky', 'the sea');

my @words = map { split ' ' } @lines;
say scalar(@words), " words: @words";

my @pairs = map { ($_, $_ * $_) } 1 .. 4;
say "@pairs";

split ' ' breaks each line into words, so three lines become eight words. The second map returns two values for each number: the number and its square. The range 1 .. 4 produces the input list.

$ perl several.pl
8 words: an old falcon a blue sky the sea
1 1 2 4 3 9 4 16

Returning no value

When the block returns an empty list (), the element is left out of the result. This lets map filter and transform in one step.

filter_map.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @values = (-3, -1, 0, 2, 5);

my @squares1 = map { $_ > 0 ? $_ * $_ : () } @values;
my @squares2 = map { $_ * $_ } grep { $_ > 0 } @values;

say "@squares1";
say "@squares2";

For values that are not positive, the conditional expression returns an empty list. The second statement does the same work in two clear steps: grep keeps the positive values and map squares them. The grep and map pipeline is usually easier to read, because each function has one job.

$ perl filter_map.pl
4 25
4 25

Building a hash

A hash can be initialized from a flat list of key-value pairs. A map block that returns two values per element builds such a list.

hash_map.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @words = qw(pear plum kiwi banana);
my %lengths = map { $_ => length } @words;

for my $word (sort keys %lengths) {
    say "$word: $lengths{$word}";
}

my @stock = qw(pear kiwi);
my %in_stock = map { $_ => 1 } @stock;

for my $word (@words) {
    say "$word is ", ($in_stock{$word} ? 'in stock' : 'sold out');
}

The first hash maps each word to its length. The second one is a lookup table: every word in @stock gets the value 1, so checking $in_stock{$word} tells whether a word is in the list. This is much faster than searching an array when there are many lookups.

$ perl hash_map.pl
banana: 6
kiwi: 4
pear: 4
plum: 4
pear is in stock
plum is sold out
kiwi is in stock
banana is sold out

Creating records

The block may contain several statements. Here we parse text lines into hash references, one record per line.

records.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @lines = ('Ada:36', 'Grace:85', 'Linus:55');

my @people = map {
    my ($name, $age) = split /:/;
    +{ name => $name, age => $age };
} @lines;

for my $p (@people) {
    say "$p->{name} is $p->{age} years old";
}

my @names = map { $_->{name} } @people;
say "@names";

The block splits $_ on the colon and returns an anonymous hash. The plus sign in +{ ... } tells Perl that the braces create a hash reference rather than start a nested block. Without it, Perl might guess wrong. The last map extracts one field from each record.

$ perl records.pl
Ada is 36 years old
Grace is 85 years old
Linus is 55 years old
Ada Grace Linus

Mapping over indexes

Inside the block, $_ holds the element, not its position. When we need the index, we map over the list of indexes instead.

indexes.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @fruits = qw(pear plum kiwi);

my @numbered = map { ($_ + 1) . ". $fruits[$_]" } 0 .. $#fruits;
say for @numbered;

my @even = map { $fruits[$_] } grep { $_ % 2 == 0 } 0 .. $#fruits;
say "@even";

The range 0 .. $#fruits lists all valid indexes of the array. The block uses the index both for the number and for the element lookup. In the second statement, grep selects the even indexes and map turns them back into elements.

$ perl indexes.pl
1. pear
2. plum
3. kiwi
pear kiwi

Nested map

A map can contain another map. This produces every combination of the elements of two lists.

nested.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @ranks = qw(A K Q);
my @suits = qw(S H);

my @cards = map {
    my $rank = $_;
    map { "$rank$_" } @suits;
} @ranks;

say "@cards";
say scalar(@cards), " cards";

The inner block also sets $_, which hides the value of the outer one. Therefore, the outer element is first copied into the lexical variable $rank. For each rank, the inner map returns two cards, and the outer map joins these lists into one.

$ perl nested.pl
AS AH KS KH QS QH
6 cards

map in scalar context

In scalar context, map returns the number of elements it has produced, not the list itself.

scalar.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @lines = ('an old falcon', 'a blue sky', 'the sea');

my @words = map { split ' ' } @lines;
my $count = map { split ' ' } @lines;

say "list:  @words";
say "count: $count";

The assignment to @words gives list context, and the assignment to the scalar $count gives scalar context. The count is the total number of values returned by all calls of the block, which is the number of words here.

$ perl scalar.pl
list:  an old falcon a blue sky the sea
count: 8

Modifying the original list

$_ is an alias to the current element, not a copy. Changing $_ inside the block changes the original array.

alias.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @names = ('  Ada ', 'Grace  ', ' Linus');

my @trimmed = map { s/^\s+|\s+$//gr } @names;
say join '|', @trimmed;
say join '|', @names;

my @changed = map { s/^\s+|\s+$//g; $_ } @names;
say join '|', @changed;
say join '|', @names;

The /r modifier makes the substitution return a modified copy, so the first map leaves @names alone. The second map runs an ordinary substitution on $_, which strips the spaces in @names itself. If changing the array is what we want, a for loop states that intent more clearly than map.

$ perl alias.pl
Ada|Grace|Linus
  Ada |Grace  | Linus
Ada|Grace|Linus
Ada|Grace|Linus

Source

map · grep · perlvar: $_

In this article we have transformed lists with Perl's map function: the block and expression forms, returning several or no values, building hashes and records, mapping over indexes, nested maps, scalar context and aliasing of $_. See also Perl grep, Perl sort and Perl references.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.