Chas Owens wrote:
> On 4/19/07, Jenda Krynicky <[EMAIL PROTECTED]> wrote:
>> From: "Chas Owens" <[EMAIL PROTECTED]>
> snip
>> > foreach is dead, long live for.
>>
>> William is dead, long live Bill?
>>
>> foreach and for are two names for the same thing and just as you can
>> call someone both William and Bill you can use foreach and for
>> interchangeably.
>>
>> foreach(my $i = 0; $i < $whatever; $i++)
>> for(my $i = 0; $i < $whatever; $i++)
>>
>> for my $x (@array)
>> foreach my $x (@array)
>>
>> for (@array)
>> foreach (@array)
>>
>> No difference to the computer. Use whichever reads best!
>
> Yes, foreach was aliased to for for backwards compatibility,
Huh? Do you have something to back up that claim?
> but, like
> telnet and rsh, it should not be used in new code.
Really? I assume you mean the protocols and not the programs?
>> I would myself use "for" for the C-style loops
>
> And this is why. As long as people think "well, I have foreach which
> is for iterating and for which is for C-style loops" they will
> continue to write C-style loops. C-style loops are bad. They are
> there for backwards compatibility. I can't think of a single for loop
> that isn't better written as a range based for loop or while loop. For
> instance
>
> standard range based loop
> for (my $i = 0; $i < 10; $i++) {}
> for my $i (0 .. 9) {}
How about:
for ( my $i = 0; $i < 10; $i += 3 ) {}
foreach my $i ( ? .. ? ) {}
> often $i winds up being used as an index which just makes me cringe.
>
> The infinite loop
> for (;;) {}
> while (1) {}
>
> The reason C programmers give for using for (;;) is that it generates
> less overhead on their platform, but, at least with my tests*,
> while(1) is more efficient in Perl.
I ran your benchmark on my computer and for(;;) and while(1) ran at about the
same speed.
$ perl -le'
use Benchmark;
my %subs = (
for => sub { my $i; for (;;) { last if $i++ > 1_000 } },
while => sub { my $i; while (1) { last if $i++ > 1_000 } },
bare => sub { my $i; { last if $i++ > 1_000; redo } },
);
Benchmark::cmpthese(-10, \%subs);
'
Rate bare for while
bare 4471/s -- -15% -15%
for 5253/s 17% -- -0%
while 5268/s 18% 0% --
$ perl -le'
use Benchmark;
my %subs = (
for => q{ my $i; for (;;) { last if $i++ > 1_000 } },
while => q{ my $i; while (1) { last if $i++ > 1_000 } },
bare => q{ my $i; { last if $i++ > 1_000; redo } },
);
Benchmark::cmpthese(-10, \%subs);
'
Rate bare while for
bare 4445/s -- -15% -15%
while 5219/s 17% -- -0%
for 5233/s 18% 0% --
John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/