in reply to infinite loop does not stop

From the final print statement in the original code, it seems the intention is to mark a random sample of the population as infected, the size of this sample being input by the user as $answerinfect. If this interpretation is correct, the OP’s code does not work correctly, even setting aside the infinite loop, because each iteration of the outer for loop infects 2 distinct individuals, so the outcome is anywhere from $answerinfect to (2 * $answerinfect) infections (depending on the amount of overlap between loop iterations).

The following code incorporates the suggestions of aitap and frozenwithjoy, and insures that exactly $answerinfect individuals are infected. I have assumed (1) that the status field records infection, 0 for uninfected and 1 for infected; and (2) that the initial population contains no infected individuals.

#! perl use strict; use warnings; use Data::Dumper; use constant { WELL => 0, SICK => 1, }; my @pop = ( { name => 'Fred', status => WELL, }, { name => 'Wilma', status => WELL, }, { name => 'Barney', status => WELL, }, { name => 'Betty', status => WELL, }, ); (my $pop = scalar @pop) > 0 or die "Empty populatio +n\n"; print "How many random infections? (Enter a number between 1 and $pop) +:\n"; chomp(my $answerinfect = <>); ($answerinfect > 0) && ($answerinfect <= $pop) or die "Invalid selecti +on\n"; for (1 .. $answerinfect) { for (my $new_infection = 0; !$new_infection;) { my $contact = int(rand($pop)); if ($pop[$contact]{status} == WELL) { $pop[$contact]{status} = SICK; $new_infection = 1; } } } print Dumper(\@pop); printf "You have infected %d %s: ", $answerinfect, ($answerinfect == 1) ? 'person' : ' +people'; print join(', ', sort map { $_->{name} } grep { $_->{status} == SICK } + @pop);

Typical output:

How many random infections? (Enter a number between 1 and 4): 2 $VAR1 = [ { 'status' => 0, 'name' => 'Fred' }, { 'status' => 0, 'name' => 'Wilma' }, { 'status' => 1, 'name' => 'Barney' }, { 'status' => 1, 'name' => 'Betty' } ]; You have infected 2 people: Barney, Betty

Some notes:

HTH,

Athanasius <°(((><contra mundum