XP is just a number | |
PerlMonks |
What's a closure?by faq_monk (Initiate) |
on Oct 08, 1999 at 00:27 UTC ( [id://690]=perlfaq nodetype: print w/replies, xml ) | Need Help?? |
Current Perl documentation can be found at perldoc.perl.org. Here is our local, out-dated (pre-5.6) version: Closures are documented in the perlref manpage. Closure is a computer science term with a precise but hard-to-explain meaning. Closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding). Closures make sense in any programming language where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures; the Python language, for example. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures. Here's a classic function-generating function:
sub add_function_generator { return sub { shift + shift }; }
$add_sub = add_function_generator(); $sum = $add_sub->(4,5); # $sum is 9 now.
The closure works as a function template with some customization slots left out to be filled later. The anonymous subroutine returned by
Contrast this with the following
sub make_adder { my $addpiece = shift; return sub { shift + $addpiece }; }
$f1 = make_adder(20); $f2 = make_adder(555);
Now Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function:
my $line; timeout( 30, sub { $line = <STDIN> } );
If the code to execute had been passed in as a string,
|
|