Tad McClellan said:
From that, I thought you were going to present a case where a C-style
loop with three arguments was preferable over Perl-style looping over
lists...
No, I suppose I wasn't entirely clear. The distinction I was making
was between iterating over the elements of a list and iterating
over the indices of a list.
[...]
I have to know when I'm
processing the last argument:
foreach my $i (0 .. $#ARGV) {
print "$ARGV[$i]";
perldoc -q vars
Right, lose the quotes. (That was an editing error.)
foreach (my $i=0; $i<=$#ARGV; $i++) {
or
foreach (my $i=0; $i<@ARGV; $i++) {
I'd say that a Perl style loop "foreach my $i (0 .. $#ARGV)" was
preferable here too.
Agreed.
Were you going to present a case where a C-style loop was preferable?
No, I wasn't planning on it.
}
Like in all of the code that you posted.
No, in the code I posted I need to know when I'm processing the last
item.
Were you going to present a case where a C-style loop was preferable?
Is there a cleaner idiom for this kind of thing that I'm not
thinking of?
print "$ARGV[0] "; # do something with the first arg
foreach my $i (1..$#ARGV-1) {
print "$ARGV[$i] ";
}
print "$ARGV[-1]\n"; # do something with the last arg
Hmm. Yes, that certainly works, but there's some duplication
of code. In this case the duplicated code is just a print, but as
I said this is a simple example.
You can generate a list of indexes using either style of loop, but
a Perl-style loop seems preferable for that.
You have presented a case where you need to know the index, but that
can be done with either type of loop.
[...]
More generally, here's the kind of thing I have in mind (pseudo-code):
First version:
foreach my $elem (@list) {
do_a_whole_bunch_of_stuff_with($elem); # multiple lines of code
}
In the second version, I need to add some minor functionality:
foreach my $elem (@list) {
do_a_whole_bunch_of_stuff_with($elem); # multiple lines of code
if (this is the first element) {
do_this_with($elem);
}
elsif (this is the last element) {
do_that_with($elem);
}
else {
do_the_other_thing_with($elem);
}
}
What I'm vaguely wishing for, but don't particularly expect to get,
is a clean way to detect, from inside the loop, whether I'm looking
at the first or last element *without* having to restructure the
loop to keep track of the current index.
I can't even think of a good way to design a language feature that
would support this (let alone think about how to implement it),
so I'll just live with the way it is now.