in reply to Re^3: Easiest way to do something only on first iteration of loop
in thread Easiest way to do something only on first iteration of loop
Hello Marshall,
When it [a state variable] is "out of scope", then next time it comes into scope it is reinitialized.
Sorry to be pedantic, but no, as the documentation says, it is never reinitialized. Consider:
use strict; use warnings; use feature qw( say state ); my $x = 42; for (1 .. 2) { for (1 .. 3) { state $x; ++$x; say "\$x = $x"; } say "state \$x is out of scope here"; say "\$x = $x"; }
Output:
16:48 >perl 1626_SoPW.pl $x = 1 $x = 2 $x = 3 state $x is out of scope here $x = 42 $x = 4 $x = 5 $x = 6 state $x is out of scope here $x = 42 16:48 >
When the inner for loop ends, state $x goes out of scope and the $x that is printed is the my $x with wider scope. But when the inner for loop is re-entered, the inner-scope $x (the state variable) retains the value it had previously: it is not reinitialized.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Easiest way to do something only on first iteration of loop
by Marshall (Canon) on May 08, 2016 at 12:21 UTC | |
by BrowserUk (Patriarch) on May 08, 2016 at 12:48 UTC |