[ Please keep your questions on the list. ] On Wed, 2005-10-19 at 12:39 +0800, angel flower wrote: > hi,perrin, > Can you tell me what meaning of this sentence: > > Making a sub that refers to a lexical variable declared outside of its > scope will ALWAYS create a closure. > > Why this happen? And what's a closure? Thanks more.
This is kind of a big question, and you'll need to do some reading. I recommend the section on closures in Programming Perl, and there's a "What's a Closure?" entry in the perlfaq7 man page, and more in the perlref man page. The problem with all of these is that they only talk about closures with anonymous subs, and closures really have nothing to do with anonymous subs. Here's a simple example: package Private; my $hidden = 0; sub increment_hidden { $hidden++; } sub get_hidden { return $hidden; } 1; # in some other piece of code.... use Private; print Private::get_hidden(); # prints 0 Private::increment_hidden(); print Private::get_hidden(); # prints 1 print $Private::hidden; # undefined variable You might have expected that $hidden would get reset to undef when it goes out of scope in the Private module. Instead, the two subs that refer to it become closures, and they get a private copy of the variable. Nothing else can access that variable at this point, but it does persist as if it were a global for those two subroutines. That's the short answer. Read some more docs, and remember that named subs can be closures. - Perrin