in reply to catching infinite loops

Apart from the obvious strategy of coding carefully so as to not create them, you can always take the precaution of throwing an alarm call in there just in case things get out of whack. The alarm will always go off, even if your logic is blown to heck. If you put the code inside an eval, you can contain the damage, such as terminating a block of code instead of the entire program.

Or, like you have done there, you can throw in a condition which you know will trigger at some point in the reasonable future. Base it on time, or a theoretical limit on the maximum number of loops you should take. As in, if you had a 1000 byte file and were trying to find all the 'e's, the loop should terminate by the 1001th iteration, since there aren't that many letters.

In fact, that is the basic strategy employed by some algorithms that can, under some circumstances, end up in an infinite loop because of unusual but valid input data.

Random Observation: Apple Computer is at 1 Infinite Loop in Cupertino, California.

Replies are listed 'Best First'.
Re: Re: Catching Infinite Loops
by Rhandom (Curate) on Apr 20, 2001 at 09:24 UTC
    Ditto but with some code...
    local $SIG{ALRM} = sub { die 'what happened?' }; eval { alarm 2; # about two seconds 1 while 1; }; if( $@ ){ print "Whew! Glad that timed out!\n"; }