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

In reply to Re: Implicit loop counter by Dominus
in thread Implicit loop counter by Anonymous Monk

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.