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
my $itemInBasket = shoppingList( "sweater" );
Assign
$itemBasket the return of
shoppingList( "sweater" ) (this much is obvious ;)
my $item = shift();
Create a new lexical in the scope of
shoppingList and assign to it the first argument.
return sub
{
my $otherItem = shift();
print "I need to buy a $item and a $otherItem.\n";
};
Return the reference to a newly created anonymous subroutine.
&$itemInBasket( "pair of shoes" );
Execute the subroutine reference stored in
$itemBasket and pass it the string
"pair of shows". Now for the tricky bit ...
my $otherItem = shift();
print "I need to buy a $item and a $otherItem.\n";
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.
HTH
_________
broquaint