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

Wow! That could be really useful. How the heck does it work and is it documented anywhere?

Update - never mind...

After some quick research and testing I see that ($0 .. !$0) only increments as it's used. So you can't just pop it into an if statement somewhere to get the current iteration (which would be very useful). You might as well just dedicate a new variable to keep count.

Interesting none the less.
  • Comment on Re^2: Is there a Perl variable to count iterations in a loop?

Replies are listed 'Best First'.
Re^3: Is there a Perl variable to count iterations in a loop?
by roman (Monk) on Dec 19, 2008 at 10:50 UTC

    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
      Interesting insight nontheless, roman. Thanks for sharing!
      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