FAQ 7.12 What's a closure?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.


7.12: What's a closure?

    Closures are documented in perlref.

    *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

    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


Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.


    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

Site Timeline