Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a special variable that I can access to get the current loop count within a "foreach" or "while" loop ? For example: foreach ( @lst ) { bla bla bla print "you are on line $#@ \n"; } Where $#@ is some special variable that is the current loop count.

Replies are listed 'Best First'.
Re: Implicit loop counter
by Dominus (Parson) on Mar 12, 2000 at 23:43 UTC

    I keep thinking that it wouldn't be so hard to add this. Of course, there's the question of what to call it, but I imagined that it would be OK to name it ${^Index}, and then have a pragma like use index; that would alias ${^Index} to $# so that you could just call it $#. Another possibility is that you could just use $# directlry---I have a suspicion that there is no program anywhere that actually uses $# at present.

    To get it to work, you would need to arrange that any for block that contained a mention of ${^Index} would have a special lexical variable allocated on its pad. You would also need to have an index in the OP node for the for block that pointed to this pad entry. Then each time through the loop, Perl would look at the index, and if it was defined, would increment the referred-to variable.

    The downside of all this is that it might slow down all loops, even those that didn't use ${^Index}, because they would have to look to see if it was there at run time. However, if the for code already keeps an iteration counter around (this is possible, although I haven't checked) one might be able to borrow it for free, or almost for free.

    It would probably be a good project for an intermediate guts hacker. I've had it on my to-do list for a long time, but I never get around to doing it. Maybe it'll be ready for 5.7.

    an iteration counter
Re: Implicit loop counter
by Benedictine Monk (Novice) on Mar 14, 2000 at 15:16 UTC
    Okay but... Why don't you just do:
    my $_index; foreach (@list) { blah(); print "You are on line ", $_index++, ".\n"; }
    It seems pretty simple to me. Am I missing something?
Re: Implicit loop counter
by Anonymous Monk on Mar 12, 2000 at 22:31 UTC
    If you're reading from a file (with the <> operator), you can use the $. special variable. If not, then you'll have to do explicit loop control, with the usual for(;;) form.
RE: Implicit loop counter
by Anonymous Monk on Mar 12, 2000 at 22:51 UTC
    No. I'm afraid not.
Re: Implicit loop counter
by Keef (Sexton) on Dec 31, 2000 at 07:09 UTC
    There's always
    $e = 1; foreach $line (@LINES) { print "You are on line $e"; $e++; }