Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: do/redo or for(;;): what's Kosher?

by tune (Curate)
on Jan 03, 2002 at 22:42 UTC ( #136032=note: print w/replies, xml ) Need Help??

in reply to do/redo or for(;;): what's Kosher?

I prefer
while (1) { last if...; }
It's more readable (IMHO).


Replies are listed 'Best First'.
Re^2: do/redo or for(;;): what's Kosher?
by Aristotle (Chancellor) on Jan 04, 2002 at 00:05 UTC

    Absolutely agree. Personally I find: the Perl way of doing things is either while() or for (@list). This is for a variety of reasons.

    First of all, if you have a loop, it should be obvious that it is a loop. (To take it to extremes, that's what BASIC's GOSUB did wrong - it is a subroutine call, but the called place doesn't look like a subroutine.)

    Also, the for(;;) form is to be avoided; most of the time you can write it as for (@list). Perl understands the notion of a list natively so you should not concern yourself with index variables. This eliminates an entire class of coding errors - the fencepost errors which consist in mostly overlooking nasty special conditions that result in the loop executing once more or less than it should. for(;;) also is inefficient (internally, it is handled like a while () {} continue {} construct).

    { ... ; redo } has its place just like for(;;) is occasionally useful - but for the sake of your own sanity you should not make either of them a habit.

      And here's the benchmark to prove it:
      #!/usr/bin/perl -w use strict; use Benchmark; Benchmark::cmpthese(10_000, { 'C-style' => sub { for (my $i = 0; $i <= 1000; $i++){ undef } }, 'foreach' => sub { for my $i (0..1000) { undef } } }); __END__ Benchmark: timing 10000 iterations of C-style, foreach... C-style: 5 wallclock secs ( 5.20 usr + 0.00 sys = 5.20 CPU) @ 19 +23.08/s (n=10000) foreach: 4 wallclock secs ( 3.73 usr + 0.00 sys = 3.73 CPU) @ 26 +80.97/s (n=10000) Rate C-style foreach C-style 1923/s -- -28% foreach 2681/s 39% --

      By the way: does perl have absolutely _no_ optimisation for for (;;) without any expressions in its parens? I find that a bit hard to believe.

      2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

        $ perl -MO=Deparse -e "while(1){die}" for (;;) { die; } -e syntax OK
        which tells me that Perl considers while(1) and for(;;) to be the same, which means it does optimize for(;;) into a simple infinite loop.

                - tye (but my friends call me "Tye")

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://136032]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2020-09-20 08:38 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (120 votes). Check out past polls.