On Wed, Aug 16, 2000 at 11:42:20AM -1000, Tim Jenness wrote:
> What about:
>
> for (0..$#array) {
> print $array[$i], " is at index ", $i, "\n";
> }
>
> I use that whenever I need to loop over indices of two arrays at once.
I use it myself ;)
Iterating over an array in terms of the array variable instead of the array
index provides a useful level of abstraction in a for/foreach loop. It adds
a certain beauty to a programming language to have a for loop without the
need to define a lower bound, an upper bound and a counter.
However, the abstraction breaks down as soon as you need to access the
index as well as the variable. This can be seen in relation to iterating
over an array of objects:
foreach $object (@array) {
$object->getline;
$object->parseline;
$object->printline;
}
Here we are clearly dealing with objects.
foreach $i (0..$#array) {
$array[$i]->index = $i;
$array[$i]->getline;
$array[$i]->parseline;
$array[$i]->printline;
}
While here we are dealing with array variables and indexes.
There is nothing wrong with this. In a lot of circumstances a C-style "for"
or a list operator will be the right thing to do. The thrust of the RFC is
to allow continued abstraction of a for loop when both the variable and the
index are required.
Having said that, I appreciate that this is not an essential feature and
that it is little more than syntactic sugar. I don't intend to engage in
hard advocacy.
John
--
"The Mosaic code has replaced the law of the jungle."
James Joyce - Ulysses