Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Re: (Ovid) Re: Sub Definitions Within Subs: Best Way to Exploit

by htoug (Deacon)
on Oct 11, 2001 at 09:15 UTC ( [id://118161]=note: print w/replies, xml ) Need Help??


in reply to Re: (Ovid) Re: Sub Definitions Within Subs: Best Way to Exploit
in thread Sub Definitions Within Subs: Best Way to Exploit

It does need to be inside another sub. The code has to be something like:
sub baz { my $foo=shift; sub bar { print $foo; } } baz("abc"); bar; baz("123"); bar;
which will print abcabc. The change to the $foo variable in the second call does not affect subroutine bar. It has a 'closed', localised and personal $foo variable, that cannot be changed by outside influences - only by bar itself. Thus the name 'closure'.

Replies are listed 'Best First'.
Definition of a Closure
by perrin (Chancellor) on Oct 11, 2001 at 18:09 UTC
    Your explanation makes sense, but it isn't correct. Based on the number of times I've had this conversation, I'd say there is massive misunderstanding around the word "closure" in the Perl community.

    Here's a definition of closure from Damian Conway:

    "In Perl, a closure is just a subroutine that refers to one or more lexical variables declared outside the subroutine itself" - OO perl, p 56.

    I grabbed that quote from a post on the Perl6 list, but I've used that as my standard definition of closure ever since the book came out. It's really the only one I've seen that makes sense.

    Note that merlyn also agrees with me, as shown here in this post to the mod_perl list.

      Quite true, but you should also include the last sentence of the section:

      "That's all there is to a closure: a subroutine that preserves any lexical variables it's using, even after they become invisible everywhere else." OO-Perl pg.57

      Closures are only interesting (for some definition of interesting) when the lexical is invisible.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-03-28 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found