I am attempting to randomly infect a certain number of people in a population notated by @pop (not shown). The variable $pop stores the index size of the array that contains my population. As of now this piece of code works but is still failing in one small area. Everytime it encounters a second draw that is equal to the first draw, it produces a number and prints it although it doesn't belong to either the first or second draw.

sub randompick_infect { my $range = $pop; $rand = int(rand($range)); print "$rand\n"; $pop[$rand]{status} = 1; } print "How many random infections? \n"; my $answerinfect = <>; for ($i=1; $i<$answerinfect; $i++){ randompick_infect; $firstcontact = $rand; print "first contact $firstcontact\n"; do{ randompick_infect; $secondcontact = $rand; print "second contact $secondcontact\n"; if ($secondcontact == $firstcontact){ randompick_infect; } else { $j=-1; } }while($j!=-1); } printarray; print "You have infected $answerinfect people.\n";

Any help appreciated.


In reply to infinite loop does not stop by Anonymous Monk

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.