icon Top 9 categories map      RocketAware > Perl >

What's a closure?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

What's a closure?

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 add_function_generator() isn't technically a closure because it refers to no lexicals outside its own scope.

Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created.

    sub make_adder {
        my $addpiece = shift;
        return sub { shift + $addpiece };
    }

    $f1 = make_adder(20);
    $f2 = make_adder(555);

Now &$f1($n) is always 20 plus whatever $n you pass in, whereas &$f2($n) is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around.

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, '$line = <STDIN>', there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope.


Source: Perl FAQ: Perl Language Issues
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: What is variable suicide and how can I prevent it?

Previous: How can I tell if a variable is tainted?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: PERL




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq7/What_s_a_closure_.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments