Hi - Major novice here. I'm trying to write a code that starts with a user defined number (lets say "N"), picks a random number between 1 and N (lets say "R"), pushes R onto an array, subtracts R from N, then picks the next random number from (N-R), pushes the new number onto the array...etc...and loops this until (N-R)==0.

The code I have seems to go into an infinite loop or something... any help would be great and if there's an obvious solution, I apologize in advance. Thanks!

use warnings; use strict;
my @list;
print "Enter number of OTUs:";
my $start = <STDIN>;
do {
my $rand = int(rand($start));
push (@list, $rand);
$start-=$rand;
} until ($start ==0);

print "@list";

"do" is not really a loop but if you use "until" or "while" with it you can get it to act like a loop. The problem with your code is that $start never has a chance to equal zero so the "do" block just keeps getting repeated over and over. Thix will help you see whats going on:

use warnings;
use strict;
my @list;
print "Enter number of OTUs:";
my $start = <STDIN>;
chomp $start;
do {
my $rand = int(rand($start));
print "rand = $rand\n";
push (@list, $rand);
$start-=$rand;
print "\$start = $start\n";
} until ($start == 0);

print "@list";

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.