| | |
perl loop problem (from a beginner)
![]() |
•
•
Join Date: Apr 2009
Posts: 7
Reputation:
Solved Threads: 0
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";
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:
Perl Syntax (Toggle Plain Text)
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";
![]() |
Similar Threads
Other Threads in the Perl Forum
- Previous Thread: Dynamic Array
- Next Thread: Help! comparing two sequences through perl
| Thread Tools | Search this Thread |





