Reputation: 16115
I want to apply a function to every item of a list and store results similar to map(function, list)
in python.
Tried to pass a function to map, but got this error:
perl -le 'my $s = sub {}; @r = map $s 0..9'
panic: ck_grep at -e line 1.
What's the proper way to do this?
Upvotes: 11
Views: 6181
Reputation: 1817
try : map { $s->($_) } (0..9)
instead of map $s 0..9
explanation : in you example, $s
is a reference to a subroutine, so you must dereference it to allow subroutin calling. This can be achieved in several ways : $s->()
or &$s()
(and probably some other ways that I'm forgetting)
Upvotes: 5
Reputation: 118635
It's not too different from Python.
@results = map { function($_) } @list;
@results = map function($_), @list;
or with "lambdas",
@results = map { $function->($_) } @list;
@results = map $function->($_), @list;
Upvotes: 2
Reputation: 42421
If a scalar variable holds a code reference -- for example:
my $double = sub { 2 * shift };
You can invoke the code very much the way you would in Python, like this:
$double->(50); # Returns 100.
Applying that to a map
example:
my @doubles = map $double->($_), 1..10;
Or this way:
my @doubles = map { $double->($_) } 1..10;
The second variant is more robust because the block defined by the {}
braces can contain any number of Perl statements:
my @doubles = map {
my $result = 2 * $_;
# Other computations, if needed.
$result; # The return of each call to the map block.
} 1..10;
Upvotes: 9
Reputation: 80425
my $squared = sub {
my $arg = shift();
return $arg ** 2;
};
then either
my @list = map { &$squared($_) } 0 .. 12;
or
my @list = map { $squared->($_) } 0 .. 12;
or maybe
my $squared;
BEGIN {
*Squared = $squared = sub(_) {
my $arg = shift();
return $arg ** 2;
};
}
my @list = map { Squared } 0 .. 12;
Upvotes: 5