Perl: Map Function to List
Map Function to List
Use map
to apply a function to a list.
map { expression } list
-
Evaluates expression for each element of list. Any
$_
in expression is replaced by a element in list. Returns the new list. (In scalar context, returns the list length.) map { f $_ } list
- Use function f on the elements.
# -*- 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];
$_
-
a builtin variable that represent a argument given to a subroutine.
$_
is also the default input for regex to match, and in general$_
represents a default argument. @_
- the entire arguments as array.
$_[0]
- The first argument.
The (0..10)
generate a list from 0 to 10.
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.
grep {f $_} list
- where function f's result is intrepreted as true/false. items which f returns false are removed.
grep {expression ;} list
- using a expression
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 ]