Tweet

Using the Perl map() function

Introduction

The map function is used for transforming lists element-wise: given a list and a code block, map builds a new list (or hash) with elements derived from the corresponding elements of the original.

The basic syntax is

    @out = map { CODE } @in;

where CODE is some perl code that is given an element of the list as $_ and returns the replacement value for the new list.

Example 1

Say you have a list of names, and you want to capitalise them all. We can use map along with the built-in function ucfirst to do them all at once:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @names = qw(bob anne frank jill);
    my @capitalised_names = map { ucfirst $_ } @names;

    foreach my $name (@capitalised_names) {
        print "$name\n";
    }

This produces the output:

    Bob
    Anne
    Frank
    Jill

Example 2: Multiple outputs per input

If your code block returns a list for each element, all the lists are concatenated into the result:

    #!/usr/bin/perl
    use strict;
    use warnings;

	my @names = qw(bob anne frank jill);

    my @everyone = map {
        $_, $_ . "'s dog", $_ . "'s cat"
    } @names;

    foreach my $name (@everyone) {
        print "$name\n";
    }

This produces the output:

    bob
    bob's dog
    bob's cat
    anne
    anne's dog
    anne's cat
    frank
    frank's dog
    frank's cat
    jill
    jill's dog
    jill's cat

Example 3: Producing a hash as output

Generating a hash is almost identical to earlier examples:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @names = qw(bob anne frank jill);

    my %lengths = map { $_ => length $_ } @names;

    while (my ($name, $length) = each %lengths) {
        print "'$name' has $length characters\n";
    }

This produces the output:

    'bob' has 3 characters
    'anne' has 4 characters
    'frank' has 5 characters
    'jill' has 4 characters

Example 4: Restructuring data

Say you have some data stored as a list of hashrefs and you want to convert it to a hash based on some key field id.

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @array = ({
        id      => 1,
        name    => 'Bob',
    },{
        id      => 2,
        name    => 'Anne',
    },{
        id      => 3,
        name    => 'Frank'
    });

    my %hash = map { 
        $_->{id} => { name => $_->{name} } 
    } @array;

    for my $id (1..3) {
        my $name = $hash{$id}->{name};
        print "User $id: $name\n";
    }

This produces the output:

    User 1: Bob
    User 2: Anne
    User 3: Frank

See also

    perldoc -f map
[Top]