in reply to Take the next step into closures (Re: subs as args)
in thread subs as args

A closure is an anonymous subroutine that's been created by another subroutine.
Not quite. That's a bad meme that perists, despite our efforts to the contrary.

A closure is subroutine that has captured its lexical environment which has now gone out of scope.

This is orthogonal to the concept of an anonymous subroutine, which may or may not need to be "closed". In other words, the properties of "having a name" and "being a closure" are uncorrelated.

Here's a named subroutine that's a closure:

BEGIN { my $current = 0; sub gimme_next { ++$current } }
This named subroutine gimme_next is a closure. And here's an example of an anonymous subroutine which is not a closure:
my $foo = sub { 2 * shift };
So, please don't confuse anonymous subroutine with closure: they're really different things.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: •closures are NOT anonymous subroutines necessarily
by itub (Priest) on Jan 20, 2005 at 22:08 UTC
    I realize this is an old post, but I just came from 423779...
    A closure is subroutine that has captured its lexical environment which has now gone out of scope.
    For completeness, I would add that not all closures are subroutines; regular expressions that use the (?{}) construct can also be closures. For example,
    sub a { my $i = 0; # note that the regex is compiled only once () = shift =~ /a(?{print $i++})/g; } a("ababa"); # prints 0 1 2 a("ajaja"); # prints 3 4 5

    I don't know if these regular expressions are implemented internally as subroutines, but they certainly don't look like subroutines, so people are often surprised to see this behavior.

Anon subs are a good way to introduce closures
by dragonchild (Archbishop) on Jul 08, 2002 at 17:20 UTC
    Of course, you are absolutely correct.

    However, I maintain that closures are an extremely difficult thing for non-functional programmers to grasp. Using an anonymous subroutine returned from a closure-generator gives someone the idea of what's going on so that they can at least grasp the basic feel.

    I say this cause that's how I learned about them. This isn't to say that in an environment where someone could be guaranteed to have the learner's attention for more than one reading, the more correct notion should be pushed.

    I guess what I'm saying is that anon subs are a tool. Closures are a concept. I often implement the concept "closure" using the tool "anon sub". (Just like I sometimes prefer implmenting the concept "object instance" using the tool "blessed closure".)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.