Content deleted Content added
→Closures in Perl: Clarification: not every lexical scope is a closure (in Perl 5). |
|||
Line 32:
This isn't right. In perl6 blocks will technically be closures, but thats pretty obscure stuff afaik. In perl5 blocks aren't closures. [[User:Demerphq|Demerphq]] 19:09, 7 April 2006 (UTC)
Scope != closure. A scope is an environment where you can get at a particular value via a particular variable name; a closure is a coderef that remembers the lexical scope where it was born. A lexical scope arises every time execution passes into a given block (or file), but you don't create a closure (at least in Perl 5) until you take a reference to a function that uses a lexical from its environment. That function has to be able to see that lexical in order to run, so the coderef has to wrap up (a piece of) the current lexical scope along with the function. It is this wrapping of state with functionality that makes a closure. (Which is more general than objects: You can take two or more coderefs that close over the same variable, if you want.) [[User:Eritain|eritain]] ([[User talk:Eritain|talk]]) 07:27, 26 October 2010 (UTC)
Regarding the "acts as an object" comment, I was thinking of a closure like this:
Line 88 ⟶ 90:
[[user:bjt|bjt]]
That's a scope, but I'd hesitate to call it a closure. The distinctive thing about closures is that you can (potentially) take multiple references to the same sub, and get it wrapped up with a different environment each time. In this example, we know from compile time that there is one and only one %cache, so no matter how many times I say \&fib there is never a need to clarify which %cache we mean, and therefore no reason to wrap any environment with the coderef. [[User:Eritain|eritain]] ([[User talk:Eritain|talk]]) 07:27, 26 October 2010 (UTC)
----
IMO the example ''was'' too complex. Also, Perl is a heinous language for explaining computer science concepts (e.g., you have to use "shift" to peel off arguments --- utterly obscure --- not to mention all the other random syntactic noise that comes with Perl). I replaced it with a more basic explanation that just conveys the idea of lexical scope capture. I used ML, which has a far more concise and pseudocode-like syntax than Perl.
|