It's a closure because the sub foo refers to $q, which is a lexical variable delcared in the enclosing scope. Now, for the rest of the life of this Perl interpreter, the $q inside of the foo subroutine will always have the same value it did the first time this code was run, no matter what you do in the main part of this program. That means you will get crazy results where CGI.pm appears to be caching data from previous requests. | [reply] |
I was going to tell you why it's not a closure, but fortunately I checked first, and of course, you are right.
I doubt your central assertion that this sort of thing happens all the time though. How many times do you see named subroutines declared inside loops? Almost never. And I have never heard of anyone accidentally creating a closure.
Personally, I find using closures a liberating experience, and since they make some hard things easy, actually reduce bugs.
| [reply] |
| [reply] |
| [reply] |
It's a closure because it contains a reference to a lexical variable ($q) from a parent scope. It could cause problems if later you reassigned $q and thought it would change inside the sub, or thought it go away after the scope of $q ended.
| [reply] |