P is for Practical | |
PerlMonks |
Re^2: Automatic Loop Counter not in perlby liverpole (Monsignor) |
on Aug 21, 2007 at 13:33 UTC ( [id://634080]=note: print w/replies, xml ) | Need Help?? |
++b4swine for a nice meditation, and ++roboticus for further expanding on the idea.
Many have been the times I've gone from having a simple foreach loop to a for loop, just because I realized that the indices would be required. For example, let's say I started with a straightforward:
Then I realize that I need the index each time through the loop, for whatever reason. Again, for simplicity's sake, let's assume the index is only needed for display purposes. Even so, it requires changing from a foreach loop to a for loop, and adding a line to set some variable to the next item in the list each time:
But wouldn't it be nice if there were a default variable set to the index? Then I could make minimal changes to the original foreach loop:
I like roboticus' idea of having an array or hash to hold multiple levels of the variable. Ideally, there would be both, a scalar variable which holds the index of the current block, and an array or hash holding the indices from all loops. The only thing I would suggest to do differently is find a special variable to replace $loopcount. An obvious choice might be $#, which is already deprecated in its current use -- from perlvar:
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
In Section
Meditations
|
|