in reply to Loop counter only works for 2
Uhm.. oh dear :---)
From just a quick glance at your code:
You should nearly always use foreach (@list) rather than for($i;$c;$n) - even if you really need a counter,
is better than the corresponding for(;;) construct. It is more efficient (yes, it is), and it removes fencepost errors - you cannot make a mistake on the condition that checks whether you have arrived on your last iteration. With the for(;;) form it is common to overlook nasty special cases that make the loop run once too much or too little.foreach my $i (0 .. 100)
Having said that, it is even better to do
thanforeach my $element (@array) { print $element; }
If you really really need the $i for other purposes besides accessing the @array, it is often still better to do something likeforeach my $i (0 .. 9) { print $array[$i] }
or maybemy $i = 0; foreach my $element (@array) { print "$i $element"; $i++ }
my $i = -1; foreach my $element (@array) { $i++; print "$element $i"; }
You should really check out Mark-Jason Dominus's excellent program repair shop series on www.perl.com. There is some very helpful advice there to get you started on writing better Perl.
|
|---|