++Thanks to all who replied. I think I've got this. It's not the value of the lexical that's captured by the closure, it's the instance, as the following illustrates:

sub make_closures { my $j = shift; return (sub {++$j;}, sub {print $j, "\n";}); } my ($bump1, $print1) = make_closures(5); my ($bump2, $print2) = make_closures(10); &$print1; &$bump1; &$print1; &$print2; &$bump2; &$print2;

which prints

5 6 10 11

I.e., each call to make_closures creates an instance of $j which is shared by bump and print, but unique to each call to make_closures. Hmmm. The ability to create at runtime multiple instances of a a thingy encapsulating data and behaviour. Sounds like the road to Objects.

In other news: sorry about the typo, I was rushing out the door ("But PerlMonks is work related"). Should've waited until the morning.

Chromatic: I know that calling &sub turns off parameter checking -- it is that you warn of?

Again, Thanks to all.

-- Dinosaur


In reply to Re: Closure Confusion by Dinosaur
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.