FAQ 7.13 What's a closure?

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

Threaded View
This is an excerpt from the latest version perlfaq7.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


7.13: What's a closure?

    Closures are documented in perlref.

    *Closure* is a computer science term with a precise but hard-to-explain
    meaning. Usually, 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 are most often used in programming languages 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 non-closure 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 anonymous subroutine returned by add_function_generator() isn't
    technically a closure because it refers to no lexicals outside its own
    scope. Using a closure gives you a *function template* with some
    customization slots left out to be filled later.

    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

    Another use for a closure is to make a variable *private* to a named
    subroutine, e.g. a counter that gets initialized at creation time of the
    sub and can only be modified from within the sub. This is sometimes used
    with a BEGIN block in package files to make sure a variable doesn't get
    meddled with during the lifetime of the package:

            BEGIN {
                    my $id = 0;
                    sub next_id { ++$id }

    This is discussed in more detail in perlsub, see the entry on
    *Persistent Private Variables*.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Re: FAQ 7.13 What's a closure?

PerlFAQ Server posted:
Quoted text here. Click to load it

I don't want to start off a language war but isn't this information out
of date?

Quoted text here. Click to load it

def make_adder(addpiece):
        def adder(n):
                return addpiece + n
        return adder
f1 = make_adder(20)
f2 = make_adder(555)

http://rjy.org.uk /

Re: FAQ 7.13 What's a closure?


Quoted text here. Click to load it

It is probably out-of-date, but also probably using a different
definition. It's not really useful to the answer in the Perl FAQ, so I
just deleted that part.


Re: FAQ 7.13 What's a closure?

  R> PerlFAQ Server posted:
  >> Note that some languages provide anonymous functions but are not capable
  >> of providing proper closures: the Python language, for example.

  R> I don't want to start off a language war but isn't this information out
  R> of date?

  >> sub make_adder {
  >> my $addpiece = shift;
  >> return sub { shift() + $addpiece };
  >> }
  >> $f1 = make_adder(20);
  >> $f2 = make_adder(555);

  R> def make_adder(addpiece):
  R>         def adder(n):
  R>                 return addpiece + n
  R>         return adder
  R> f1 = make_adder(20)
  R> f2 = make_adder(555)

i am not a python expert (or even a newbie, thankfully!) but a quick
google found this little nugget:


    In some languages, the variable bindings contained in a closure
    behave just like any other variables. Alas, in python they are
    read-only. This is similar to Java, and has the same solution:
    closing container objects. Closure of a dictionary or array
    won't let you assign a new dictionary or array, but will let you
    change the contents of the container. This is a common use
    pattern - every time you set a variable on self, you are
    changing the contents of a closed dictionary.

with perl's closures (and with other langs that fully support them) you
can do this:

sub make_up_down_counter {

    my $counter ;

    return sub { $counter }, sub { $counter++ }, sub { $counter-- } ;

my( $get_counter, $up_count, $down_down ) = make_up_down_counter() ;

and you can do that multiple times and only those 3 returned subs can
access their shared counter (they are all closed over it). using a hash
ref for that seems to be one python solution but that is overkill when
all you need to close over is a scalar. other pages comment on how
python doesn't really have anon subs but a clumsy lambda thing. and
others comment that using named subs for this works but is clumsy.

maybe the faq shouldn't mention python here but it is correct in that
doesn't seem to have true closures as other dynamic langs do. wierd
workarounds with limitations don't count.


Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

Re: FAQ 7.13 What's a closure?

Uri Guttman posted:
Quoted text here. Click to load it

Thanks for the explanation - it's clearly a more subtle issue than I had

http://rjy.org.uk /

Site Timeline