On Wed, Sep 19, 2001 at 04:20:25PM -0400, Bradshaw, Brian wrote:
>
> As for the for loop, well, I may get that advanced some time.
A for loop, or a foreach, is not advanced; it's very basic Perl. If your
learning material didn't impress upon you the usefullness or usability of
these constructs you should probably get better learning material.
> Is there an advantage to using for loops over while loops?
That's like asking if there's an advantage to using a car over a truck to
get somewhere. It depends on the situation.
When iterating over an array there is a definite advantage to using a
foreach loop rather than a while loop. Consider:
foreach my $ele (@array) {
...
}
while (@array) {
my $ele = shift(@array);
...
}
Even ignoring the (slight) difference in the amount of code, the while loop
is slower (due to the shift, and AFAIK), and destructive. There are other
ways of coding the while loop, such as:
my $i = 0;
while ($i < @array) {
my $ele = $array[$i];
...
$i++;
}
The while loop is no longer destructive, but you've just added two extra
lines. As you can see, the foreach loop is shorter and more elegantly
descriptive of what exactly it's doing.
Michael
--
Administrator www.shoebox.net
Programmer, System Administrator www.gallanttech.com
--
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]