Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

What exactly is a closure?

by John M. Dlugosz (Monsignor)
on Jul 12, 2001 at 22:51 UTC ( #96143=note: print w/replies, xml ) Need Help??

in reply to Unusual Closure Behaviour

According to the perlref page, only anonymous subs are closures. Examples elsewhere show that named subs don't "nest" the same way.

However, my experiments indicate that they work as closures, the way I did it.

So, I think the real difference is that just declaring a nested sub creates the sub at compile time. An anonymous sub is created at run time. My using eval to make the named sub appear at run time accomplished the same thing.

So, I think the real distinction is: A sub is a closure if it is created after the run-time behavior of my has occured. A sub that is formed after my is seen at compile-time can refer to that variable, but does not act as a closure. Unless the block containing that lexical variable is executed more than once, that doesn't matter.

The Perl compiler is coded to warn about named subs, but that is not the condition is should be checking for. It warns about cases that do work correctly, because the real requirement is that the sub be formed after the my is run.

A named sub can become a closure if it is delayed using eval, and an anonymous sub can be un-closed if it is hastened using BEGIN.

Could someone familiar with perlguts and the actual internal trees confirm or clarify this?


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://96143]
[Happy-the-monk]: (now all you need to do is answer: "no, for money." ;-))

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2018-04-20 11:49 GMT
Find Nodes?
    Voting Booth?