in reply to Closures clarification

If I'm not mistaken, neither of your examples are closures. According to Intermediate Perl, a closure is "just a subroutine that references a lexical variable that has gone out of scope".

In your first example, while there is an anonymous subroutine reference passed to the find() function, it doesn't reference any lexical variables. In your second example, 1) there is no subroutine, and 2) the $a enclosed in braces is a different variable than the one outside of them.

Note also that your first example was incorrect. It should have been:

use File::Find; my $total_size = 0; find(sub {$total_size += -s if -f}, '.'); print $total_size, "\n";
You were missing the "use" statement, missing a "(" in the find function, and the "{" in the sub definition was misplaced.

An example of a closure from Intermediate Perl) is as follows:
use File::Find; my $callback; { my $count = 0; $callback = sub { print ++$count, ":$File::Find::name\n" }; } find($callback, '.');
So, here the subroutine is a closure because it refers to the lexical variable $count.

Hope this helps.

memnoch

Gloria in Excelsis Deo!

Replies are listed 'Best First'.
Re^2: Closures clarification
by lodin (Hermit) on Dec 04, 2007 at 14:52 UTC

    If I'm not mistaken, neither of your examples are closures. According to Intermediate Perl, a closure is "just a subroutine that references a lexical variable that has gone out of scope".

    The anonymous subroutine passed by reference to find does bind a lexical variable ($total_size). By most definitions (e.g wikipedia's), that subroutine is then a closure. The variable doesn't have to have gone out of lexical scope. The important part is that the subroutine deeply binds the variable, and the variable may go out of scope.

    lodin

    PS. The code should read sub { instead of { sub, but that's not important for the question at hand.

      Thanks lodin...I missed that other typo! I have addressed it in my previous posting. But as far as whether it was a closure or not, according to Intermediate Perl, the lexical variable needs to have gone out of scope for the subroutine to be a closure....that's what I was going off of.

      memnoch

      Gloria in Excelsis Deo!
Re^2: Closures clarification
by fenLisesi (Priest) on Dec 04, 2007 at 14:11 UTC
    And what else is he missing?
    use File::Find; my $total_size = 0; find({sub $total_size += -s if -f}, '.'); print $total_size, "\n";
    You were missing the "use" statement and a "(" in the find function.
      Thanks fenLisesi....I missed that other typo...I have fixed it in my original posting as well.

      memnoch

      Gloria in Excelsis Deo!