How can I apply a function to a list using a map?

I want to apply a function to each element of a list and save results similar to map(function, list) in python.

I tried to pass a function to display, but got this error:

 perl -le 'my $s = sub {}; @r = map $s 0..9' panic: ck_grep at -e line 1. 

What is the right way to do this?

+7
perl map
source share
4 answers

If the scalar variable contains a link to the code - for example:

 my $double = sub { 2 * shift }; 

You can call the code in the same way as in Python, for example:

 $double->(50); # Returns 100. 

Applying this to a map example:

 my @doubles = map $double->($_), 1..10; 

Or so:

 my @doubles = map { $double->($_) } 1..10; 

The second option is more reliable, because the block defined by the brackets {} 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; 
+7
source share

try: map { $s->($_) } (0..9) instead of map $s 0..9

Explanation: in your example, $s is a reference to a subroutine, so you must dereference it to allow subroutine calls. This can be achieved in several ways: $s->() or &$s() (and maybe some other ways that I forget)

+5
source share
  my $squared = sub { my $arg = shift(); return $arg ** 2; }; 

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; 
+4
source share

It is not too different from Python.

 @results = map { function($_) } @list; @results = map function($_), @list; 

or with "lambdas",

 @results = map { $function->($_) } @list; @results = map $function->($_), @list; 
+2
source share

All Articles