Apart from that your sub make_closures doesn't return the array of closures so the code as supplied doesn't do anything , you have to realise that the reference to $j inside each of you generated closures is a reference to the $j in the sub make_closures(). Ie. They all refer to the same variable.

Here's a simple mod of your code that demonstrates the behavious that you were looking for... Maybe it will help clarify things.

#! perl -sw use strict; sub make_closures { my $j = 0; my @closures; while (++$j < 7) { my $jj = $j; push (@closures, sub {print $jj, "\n";}); } return @closures; } foreach my $sub (&make_closures) { $sub->(); } __DATA__ C:\test>205818 1 2 3 4 5 6

Here, I am creating a new var $jj inside the loop each time around and giving it the value, therefore each generated sub has its own independant variable/value, and the $j var gets garbage collected when it goes out of scope when make_closures() terminates.


Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!

In reply to Re: Closure Confusion by BrowserUk
in thread Closure Confusion by Dinosaur

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.