Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

What exactly is a closure?

by John M. Dlugosz (Monsignor)
on Jul 12, 2001 at 22:51 UTC ( [id://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?

—John

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://96143]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-03-29 14:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found