Content deleted Content added
No edit summary |
→Examples: Added Perl examples |
||
Line 229:
$foo = create_function("$x", "return $x*$x;");
echo $foo(10);
</source>
===Perl===
[[Perl]] supports anonymous functions, as follows:
<source lang="perl">
(sub { print "I got called\n" })->(); # 1. fully anonymous, called as created
my $squarer = sub { my $x = shift; $x * $x }; # 2. assigned to a variable
sub curry (&@) {
my ($sub, @args) = @_;
return sub { $sub->(@args, @_) }; # 3. as a return value of another function
}
# example of currying in Perl
sub sum { my $tot = 0; $tot += $_ for @_; $tot } # returns the sum of its arguments
my $curried = curry \&sum, 5, 7, 9;
print $curried->(1,2,3), "\n"; # prints 27 ( = 5 + 7 + 9 + 1 + 2 + 3 )
</source>
Other constructs take "bare blocks" as arguments, which serve a function similar to lambda functions of a single parameter, but don't have the same parameter-passing convention as functions -- @_ is not set.
<source lang="perl">
my @squares = map { $_ * $_ } 1..10; # map and grep don't use the 'sub' keyword
my @square2 = map $_ * $_, 1..10; # parentheses not required for a single expression
my @bad_example = map { print for @_ } 1..10; # values not passed like normal Perl function
</source>
|