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

There is probably no such variable, but you can play with a range operator .. in scalar context:

my @letters = qw(alfa beta gama); for my $letter (@letters){ warn "iteration is ", scalar($0 .. !$0); }

The $0, resp. !$0 are just expressions which are allways true, resp. allways false. Unfortunately you cannot use 1, 0 because they are given some special meaning by the range operator.

Although this "trick" works, it is not particularly self-explainable.

Replies are listed 'Best First'.
Re^2: Is there a Perl variable to count iterations in a loop?
by ruzam (Curate) on Dec 18, 2008 at 23:00 UTC
    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.

      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