in reply to 'my' and 'state' declaration inside a loop

my $n; for (1..10000000) { $n = $_**2; } versus: my $n; for (1..10000000) { state $n = $_**2; }
In this sense, this is actually nonsense.

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

    Ok, my fist post didn't have good examples to show what I was pointing out.

    Consider a case like this where the three snippets produce the same output:

    Traditional my way:

    my $n; for (1..5) { $n++; say $n } __END__ Prints: 1 2 3 4 5

    New state way:

    for (1..5) { state $n++; say $n } __END__ Prints: 1 2 3 4 5

    I just was wondering if the fact of declaring the variable inside the loop has an extra cost compared to declaring the variable first out of the loop. But it seems like there is no difference in time cost as far as I could test anyway.

      Well, the "traditional" way is put the "my" variable in the scope of the loop.
      #!/usr/bin/perl -w use strict; use 5.10.0; ## my $n; for (1..5) { $n++; say $n } ## wrong foreach my $n (1..5) { say $n;} __END__ 1 2 3 4 5
      Update:
      Maybe my previous example was not the best. But basically if you have something to initialize before a for loop starts iterating, do it in the for loop! "state" is actually a rather rare thing. You could code Perl for a year or two between using it.