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


In reply to Re: Help with the concept of closures. by broquaint
in thread Help with the concept of closures. by DigitalKitty

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.