Perl: Map Function to List

By Xah Lee. Date:

Map Function to List

Use map to apply a function to a list.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper; $Data::Dumper::Indent=0;

sub ff {return $_[0] + 1;};

print Dumper [ map { ff $_ } (1,2,3,4)]; # → [2,3,4,5];

# ff written as embedded expression
print Dumper [ map { $_ + 1 } (1,2,3,4)]; # → [2,3,4,5];

The (0..10) generate a list from 0 to 10.

The % above is the operator for computing remainder of a division.

The Data::Dumper module is to import the “Dumper” function for printing list.

Removing Elements in a List

Use grep to remove elements in a list.

Example:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

sub ff {return $_[0] % 2 == 0}; # return true if divisible by 2

print Dumper[ grep {ff $_} (0..10)]; # ⇒  [ 0, 2, 4, 6, 8, 10 ]

Here's the same thing, where the function is embedded as a expression:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

print Dumper[ grep {$_[0] % 2 == 0} (0..10) ]; # ⇒  [ 0, 2, 4, 6, 8, 10 ]