>>>>> "Jonathan" == Jonathan e paton <[EMAIL PROTECTED]> writes:

Jonathan> A better example is the closure:

Jonathan> my $sub = sub { print "Hello " . shift . "\n" };
Jonathan> $sub->("World");

That's not a closure.  It's merely an anonymous subroutine.

A closure is a subroutine (named or not) that has access to lexical
variables that may go out of scope before the subroutine goes out of
scope.  Perl arranges for private references to the variables so that
they are kept alive as long as the subroutine is alive.

Closures most often happen with anonymous subroutines, so people tend
to get the terms mixed up.  Here's an example of a closure from a
named subroutine:

    BEGIN {
      my $private = 0;
      sub next_private { ++$private }
    }

The lexical $private is "closed" with the closure &next_private, so
that it persists beyond what it would have (the creation and immediate
execution of the BEGIN block) and stays active as long as the
subroutine &next_private is alive (the entire program execution, in
this case).

So, "closureness" (where the subroutine sees and captures external
lexical variables) and "namedness" (anon sub vs named sub) are
orthogonal properties.

Hope this helps.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<[EMAIL PROTECTED]> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to