http://www.perlmonks.org?node_id=634080


in reply to Re: Automatic Loop Counter not in perl
in thread Automatic Loop Counter not in perl

++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:

#!/usr/bin/perl -w use strict; use warnings; my @array = qw( a b c d e f g h ); # Code sample 1 -- for simplicity, just display each array item: foreach (@array) { printf "%s\n", $_; }

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:

# Code sample 2 -- Come to think of it, I want the indices too ... for (my $i = 0; $i < @array; $i++) { my $item = $array[$i]; printf "%3d. $item\n", $i + 1; }

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:

# Code sample 3 -- minor changes from the original "foreach" # loop (Code sample 1) foreach (@array) { printf "%3d. %s\n", $loopcount + 1, $_; }

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:

$# The output format for printed numbers. This variable is a half-hearted attempt to emulate awk's OFMT variable. There are times, however, when awk and Perl have differing notions of what counts as numeric. The initial value is "%.ng", where n is the value of the macro DBL_DIG from your system’s float.h. This is different from awk's default OFMT setting of "%.6g", so you need to set $# explicitly to get awk's value. (Mnemonic: # is the number sign.) Use of $# is deprecated.

s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/