in reply to Re^2: Is there a Perl variable to count iterations in a loop?
in thread Is there a Perl variable to count iterations in a loop?

Be aware. I just get burned by this hack - the range operator iterates all over its lifetime.

sub iterate { for my $item ( @_ ){ warn 'iteration '. ($0 .. !$0), "\n"; } } iterate( qw(a b c) ); iterate( 1, 2, 3, 4); iterate( 0 );

yields

iteration 1 iteration 2 iteration 3 iteration 4 iteration 5 iteration 6 iteration 7 iteration 8

Replies are listed 'Best First'.
Re^4: Is there a Perl variable to count iterations in a loop?
by pat_mc (Pilgrim) on Dec 19, 2008 at 11:27 UTC
    Interesting insight nontheless, roman. Thanks for sharing!
Re^4: Is there a Perl variable to count iterations in a loop?
by LanX (Saint) on Dec 19, 2008 at 11:29 UTC
    But this works
    my @letters = qw(alfa beta gama); for my $letter (@letters){ warn "iteration is ", scalar($0 .. !$0); } for my $letter (@letters){ warn "iteration is ", scalar($0 .. !$0); }
    I think the range-operator depends on the code position, but your sub is always at the same one. *

    Cheers Rolf

    UPDATE: well the documentation could be clearer...
    perlop

    ... The sequence number is reset for each range encountered ....
    ...in the compilation phase!!!

    (*) that's why the scalar range is known as flip-flop-operator