in reply to Help with the concept of closures.
Having worked with perl for a reasonable length of time, the concept of a closure should not prove to be so enigmatic.<plug>Perhaps Closure on Closures would be of help in shedding closures of their enigma.</plug>.
I was hoping some of you could evaluate the code below and tell me what is happening at each stage of program execution.Here we go then
Assign $itemBasket the return of shoppingList( "sweater" ) (this much is obvious ;)my $itemInBasket = shoppingList( "sweater" );
Create a new lexical in the scope of shoppingList and assign to it the first argument.my $item = shift();
Return the reference to a newly created anonymous subroutine.return sub { my $otherItem = shift(); print "I need to buy a $item and a $otherItem.\n"; };
Execute the subroutine reference stored in $itemBasket and pass it the string "pair of shows". Now for the tricky bit ...&$itemInBasket( "pair of shoes" );
Assign $otherItem the first argument. Now when we print out $item we are referring to the $item that was created when the anonymous sub was returned. It is still in existence because the anonymous sub 'held on' to $item as it was referred to inside the code (it's not quite as simple as this, but that explanation shall suffice). So the anonymous sub is maintaining the lexical state of the surrounding scope that it was created in.my $otherItem = shift(); print "I need to buy a $item and a $otherItem.\n";
_________
broquaint
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Help with the concept of closures.
by demerphq (Chancellor) on Jul 06, 2003 at 12:16 UTC |