It depends on how you write things. For example, rather than writing a function iteratively (i.e., using the loop structure), write it recursively. Catching loops is then a matter of making sure you're not trying to calculate something you've previously tried to calculate - unless there's some random stuff in your function (making it a not-function :) if you've visited the same place twice, you're in a loop.

The only thing to catch then is infinite diversions - such as, "Sum of all numbers to N" could be written:

sum nums_to_n { my $n = shift; if ($n==0) return 0; else return $n + nums_to_n ($n-1); }

This obviously loops indefinitely for $n < 0, which is not good. Usually, the answer is to make sure that your base case always occurs - that is, you can guarantee that there are certain values you can always calculate, and that you only accept values which rely, ultimately, on those values you can calculate.

updated: changed a < into &lt; .. duh..


In reply to Re: catching infinite loops by kal
in thread catching infinite loops by cLive ;-)

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.