SPUG: Loop styles: goto vs. redo

dancerboy dancerboy at strangelight.com
Tue Jul 2 01:04:00 CDT 2002


At 9:10 pm -0700 2002-07-01, Richard Anderson wrote:
>After some wrangling with my CPAN co-author over a trivial point of style,
>I'd like to throw this before the group.  For production code, which is
>better (or suggest an alternative that is better than both):
>
>START_TESTS:
>     my $not_done = 0;
>     for (...) {
>         unless (...) {
>             ...
>             $not_done = 1;
>         }
>     }
>     goto START_TESTS if $not_done
>
>or
>
>{
>     my $done = 1;
>     for  (....) {
>         unless(...) {
>             ...
>             $done = 0;
>         }
>     }
>     redo unless $done;
>}

I personally dislike goto's and their ilk, so I consider these both 
somewhat hideous.  IMHO, a better alternative is:

   my $done = 1;
   do {
       for  (....) {
           unless(...) {
               ...
               $done = 0;
           }
       }
   } while ( not $done );

or, better yet, I bet if you thought a little more carefully about 
your exit condition(s), you could simplify your flow structure and 
get rid of the $done flag altogether, maybe even being able to pack 
it into a single for statement:

   for ( <insert cleverness here> ) {
       ....
   }

Of course, it depends on exactly what you're doing -- but *usually* 
these sorts of deeply-nested control structures are unnecessary.

Whatever you do, *please* don't use a boolean variable with negated 
semantics, like "$not_done".  Otherwise, you end up with expressions 
like:

   unless ( $not_done ) {...}
   if ( ! $not_done ) {...}
   unless ( not $not_done ) {...}

These just make my brain hurt.  Even if you keep the semantics the 
same, name the variable something non-negated, like "$keep_going".

-jason

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org




More information about the spug-list mailing list