SPUG: Re: Loop styles: goto vs. redo

dancerboy dancerboy at strangelight.com
Tue Jul 2 12:50:21 CDT 2002


At 9:32 am -0700 2002-07-02, SPUG-list-owner wrote:
>  > Remember people, as ridiculous as it may (and certainly does) sound,
>>  the [s]ub word is illegal in posts to this list (thanks to Majordomo).
>>  -Tim
>
>Why not put it in a subroutine and use recursion?
>
>Zub Tests {
>     my $done = 0;
>     for (...) {
>         unless (...) {
>             ...
>             $done = 1;
>         }
>     }
>     &Tests unless $done;
>}

I realize that this might have been said in jest, but there are 
newbies on this list who might take this suggestion seriously, so...

Why not?  Because if you need to make several hundred iterations of 
Tests, you're likely to run out of memory and end up with a core dump.

Remember: every time you make a subroutine call, the interpreter has 
to push a bunch of stuff onto the stack, and then pop it off the 
stack again at the end of the subroutine.  Recursion is *good* when 
you're implementing something like a binary search or a recursive 
sorting algorithm -- i.e. where all of that stack pushing and popping 
is actually part of the algorithm you're trying to implement.  In 
such cases recursion is a clever way of getting the interpreter to do 
a lot of your work for you.  But in cases like this example above, 
where all of that stack pushing and popping is completely 
superfluous, then recursion is *bad*: it's confusing to read and it's 
a huge waste of resources.

Also, notice that if you use recursion like this, then you get a new 
scope for every iteration, which could cause complications if you 
need to access the same data each time through:  you'll need to use 
file- or package-scoped variables (i.e. globals) or accessor 
functions that *act* like globals.

Yes, TMTOWTDI, but some of those ways are simply wrong...   ;)

-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