in reply to Re: expressions as constants
in thread expressions as constants
Closures are little anonymous functions that you can assign to a scalar and call repeatedly
Not to pick nits, but that's not exactly what a closure is. What you've described is just a standard anonymous subroutine. A closure is a bit more than that. A closure captures any surrounding lexical variables, and keeps their values between calls to the subroutine. Here's the canonical example:
sub makecounter { my $count = 0; return sub { ++$count }; } my $counter1 = makecounter; my $counter2 = makecounter; for (1 .. 5) { print $counter1->(), "\n"; } print $counter2->(), "\n";
Update: another small bit of clarification. Anonymous subroutines are not necessary for creating closures. Regular subroutines will cause closure around any surrounding lexical variables, too. It's not as flexible, since you only get one closed set of lexical variables, but it works the same. Here's an example:
{ # create a scope for the closure my $count = 0; sub counter { ++$count } } for (1 .. 5) { print counter, "\n"; }
|
---|