Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Eric Strom's answer is correct, and probably what you wanted to see, but doesn't go into the details of the binding.</p> <p>A brief note about lexical lifespan: lexicals are created at compile time and are actually available even before their scope is entered, as this example shows:</p> <pre><code>my $i; BEGIN { $i = 42 } print $i; </code></pre> <p>Thereafter, when they go out of scope, they become unavailable until the next time they are in scope:</p> <pre><code>print i(); { my $i; BEGIN { $i = 42 } # in the scope of `my $i`, but doesn't actually # refer to $i, so not a closure over it: sub i { eval '$i' } } print i(); </code></pre> <p>In your code, the closure is bound to the initial lexical <code>$i</code> at compile time. However, foreach loops are a little odd; while the <code>my $i</code> actually creates a lexical, the foreach loop does not use it; instead it aliases it to one of the looped over values each iteration and then restores it to its original state after the loop. Your closure thus is the only thing referencing the original lexical <code>$i</code>.</p> <p>A slight variation shows more complexity:</p> <pre><code>foreach (@foo) { my $i = $_; sub printer { my $blah = shift @_; print "$blah-$i\n"; } printer("test"); } </code></pre> <p>Here, the original <code>$i</code> is created at compile time and the closure binds to that; the first iteration of the loop sets it, but the second iteration of the loop creates a new <code>$i</code> unassociated with the closure.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload