> If an anonymous sub doesn't close over an external variable then it isn't a closure.
And if a named sub does, it's also a closure.
Indeed two unrelated concepts.
UPDATE
I just checked the etymology, the fact that the bound variables are not accessible from the outside of their defining scope makes the sub "closed".
{
my $state = 42;
sub closed_sub {
return $state++;
}
}
say closed_sub(); # 42
say closed_sub(); # 43
Contrary to subs binding global variables, which are "open".
{
our $state = 42;
sub open_sub {
return $state++;
}
}
say open_sub(); # 42
$main::state = 666;
say open_sub(); # 666
(of course Perl allows you to bind both kinds, so it's not an exclusive attribute here)
see references from WP:
- Moses, Joel (June 1970). "The Function of FUNCTION in LISP, or Why the FUNARG Problem Should Be Called the Environment Problem". ACM SIGSAM Bulletin (15): 13–27. doi:10.1145/1093410.1093411. hdl:1721.1/5854. S2CID 17514262. AI Memo 199. A useful metaphor for the difference between FUNCTION and QUOTE in LISP is to think of QUOTE as a porous or an open covering of the function since free variables escape to the current environment. FUNCTION acts as a closed or nonporous covering (hence the term "closure" used by Landin). Thus we talk of "open" Lambda expressions (functions in LISP are usually Lambda expressions) and "closed" Lambda expressions. ... My interest in the environment problem began while Landin, who had a deep understanding of the problem, visited MIT during 1966–67. I then realized the correspondence between the FUNARG lists which are the results of the evaluation of "closed" Lambda expressions in LISP and ISWIM's Lambda Closures.
- Wikström, Åke (1987). Functional Programming using Standard ML. Prentice Hall. ISBN 0-13-331968-7. The reason it is called a "closure" is that an expression containing free variables is called an "open" expression, and by associating to it the bindings of its free variables, you close it.