Considering what else is provided by perl, (for example the $. variable), I have always felt the lack of a special variable (call it $LOOPCOUNTER), which starts from 0, and counts the number of times the innermost while, for, etc... has run. There would only be one such variable, so you could only use it in the innermost loop. Any loop would reset it to zero when starting, and increment it at each iteration.

With which you could write:

print "$LOOPCOUNTER $_\n" for @x;
instead of the painful,
print "$_ $x[$_]\n" for 0..@x-1;

In the example above, there doesn't seem to be much of an advantage, but in other situations, it would not only be handy, but much more legible, for example

print "$LOOPCOUNTER $_\n" for keys %$LoH->[$count];
is a lot nicer than
print "$_ keys %LoH->[$count]{$_}\n" for 0..(keys %LoH->[$count])-1;
or
my $count = 0; print $count++ . " $_\n" for keys %LoH->[$count];

Obviously there is an efficiency hit of having an increment for every loop iteration whether you want it or not. On the other hand, very often the counter is desirable, and having a dedicated counter might be more efficient than a lexical my variable that is often used in its place.

This is my first meditation, so please be gentle, in case this is a stupid idea.


In reply to Automatic Loop Counter not in perl by b4swine

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.