Perl FAQ 3.14: What's a "closure"?

Perl FAQ 3.14

What's a "closure"?

(Larry wrote) This is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside of the context.

In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl provides a different mechanism to do that already.

You can also think of it as a way to write a subroutine template without using eval.

Here's a small example of how this works:

    sub newprint {
	my $x = shift;
	return sub { my $y = shift; print "$x, $y!\n"; };
    $h = newprint("Howdy");
    $g = newprint("Greetings");

    # Time passes...


This prints:

    Howdy, world!
    Greetings, earthlings!

Note particularly that $x continues to refer to the value passed into newprint() despite the fact that the my $x has seemingly gone out of scope by the time the anonymous subroutine runs. That's what closure is all about.

This only applies to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with.