Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

map

perl

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?

like image 453
planetp Avatar asked Nov 18 '10 13:11

planetp


1 Answers

  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;
like image 193
tchrist Avatar answered Oct 19 '22 19:10

tchrist