in reply to Trying to understand closures
With this code you get the more expected output of 12111.#!/usr/bin/perl foo(); bar(); for (1..3) { my $x=0; sub foo { print ++$x } sub bar { print ++$x } print ++$x; }
If seems that perl is "optimizing" your loop in some very odd manner.
It may be (I did not look a the perl source) that perl is unrolling the loop so that it ends up looking something like:
That is: one $x is used for the closure and the first time through the loop and a different $x is used for the other times throught the loop.foo(); bar(); { my $x; sub foo { print ++$x; } sub bar { print ++$x; } print ++$x; { my $x; for (2..3) { print ++$x; undef $x; } } }
Update: updated the code of the second fragment to make it more clear what I think perl is doing. Added some text as well.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trying to understand closures
by ikegami (Patriarch) on Nov 24, 2006 at 05:14 UTC | |
by superfrink (Curate) on Nov 24, 2006 at 05:51 UTC | |
by ikegami (Patriarch) on Nov 24, 2006 at 05:54 UTC | |
by gam3 (Curate) on Nov 24, 2006 at 13:01 UTC |