in reply to Re: 'my' and 'state' declaration inside a loop
in thread 'my' and 'state' declaration inside a loop

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.

Replies are listed 'Best First'.
Re^3: 'my' and 'state' declaration inside a loop
by Marshall (Canon) on Aug 08, 2012 at 04:06 UTC
    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.