Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Re: Re: Help with the concept of closures.

by bobn (Chaplain)
on Jul 06, 2003 at 03:21 UTC ( [id://271718]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Help with the concept of closures.
in thread Help with the concept of closures.

Nope. Each coderef (set of coderefs in your example - it's the time that the lexical is in scope that matters) has it's own copy.

sub make_closures { my $value = shift; return sub { $value++ }, sub { print "$value\n" }, sub { $value-- }; } my ($increment, $display, $decrement) = make_closures( 3 ); print "first\n"; $display->(); $increment->(); $display->(); $decrement->(); $display->(); my ($increment2, $display2, $decrement2) = make_closures( 9 ); print "second\n"; $display2->(); $increment2->(); $display2->(); $decrement2->(); $display2->(); print "first again\n"; $display->(); $increment->(); $display->(); $decrement->(); $display->();

Result:

first
3
4
3
second
9
10
9
first again
3
4
3

That's why it needs to be lexical.



--Bob Niederman, http://bob-n.com

Replies are listed 'Best First'.
Re: Re: Re: Re: Help with the concept of closures.
by chromatic (Archbishop) on Jul 06, 2003 at 04:37 UTC

    I suspect we mean different things by the word "copy".

    Because lexical variables live in scratchpads and because a closure carries around the scratchpad where it was created, I say that a closure does not make a new copy of the variable.

    Because a new scratchpad is created on each scope entry and the closures returned bind to the new scratchpad, you say that a closure does copy the variable.

    I don't think "copy" is the right word, but I understand what you're saying and the effect is indeed accurate.

      If by "same" you mean it's the same $item it was during the life of the call to shoppingList(), even though it lives in a different scratchpad from that of all other calls to shoppingList(), then I understand what you meant. And you certainly understand what I meant. (is chromatic here the same as chromatic on slashdot? If so, I probably shouldn't argue at all.)



      --Bob Niederman, http://bob-n.com
        After some messaging, chromatic and I agree that "instance" is a better word than "copy".

        --Bob Niederman, http://bob-n.com

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-18 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found