in reply to 'my' and 'state' declaration inside a loop
In this sense, this is actually nonsense.my $n; for (1..10000000) { $n = $_**2; } versus: my $n; for (1..10000000) { state $n = $_**2; }
See Perl State.
Perl "state" is a way implement what would be called a "static" variable in 'C'. This is a way to initialize "a 'do it once' variable'" - often in a recursive subroutine.
I have not seen anything like this in a for() loop. There is no reason.
Update: Here is an example:
#!/usr/bin/perl -w use strict; use 5.10.0; foreach (1..5) { print nextNum(),"\n"; } sub nextNum { state $num =10; return $num++; } __END__ Prints: 10 11 12 13 14
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 'my' and 'state' declaration inside a loop
by nemesisgus (Acolyte) on Aug 05, 2012 at 19:31 UTC | |
by Marshall (Canon) on Aug 08, 2012 at 04:06 UTC |