The variable is captured (i.e. kept around), not the value.

I would not have expected this.

Weird. You read $i, but expect to get the value of something other than $i?

is this [...] something which can be found documented somewhere?

Closures are documented in perlsub. "If something more permanent is still aware of the lexical, it will stick around."

This means you can access the lexical beyond when it would normally be destroyed for going out of scope (which doesn't actually happen in your second snippet).

Reading the variable still gives its current value as usual.

is this a bug [...]?

Absolutely not.

Imagine if the following module didn't work because $i didn't get captured by get and set:

package Foo; my $i; sub get { $i } sub set { $i = shift; } 1
(These are true closures like your first snippet but unlike your second since $i goes out of scope at the end of the file before get and set are called.)

is this [...] a quirk [...]?

Absolutely not.

Same in JavaScript.

const subrefs = []; let i = 0; for ( let j = 3; j--; ) { i++; subrefs.push( function(){ console.log( i ); } ); } for ( const subref of subrefs ) { subref(); }
3 3 3

Same in C#

List<Action> subrefs = new(); int i = 0; for (int j = 0; j < 3; ++j ) { i++; subrefs.Add( () => Console.WriteLine( i ) ); } foreach ( var subref in subrefs ) { subref(); }
3 3 3

Same in Python

subrefs = [] i = 0 for j in range(3): i = i + 1 def subref(): print( i ) subrefs.append( subref ) for subref in subrefs: subref()
3 3 3

In reply to Re: Closures and scope of lexicals by ikegami
in thread Closures and scope of lexicals by haj

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.