perl loop problem (from a beginner)

Reply

Join Date: Apr 2009
Posts: 7
Reputation: LSU_223 is an unknown quantity at this point 
Solved Threads: 0
LSU_223 LSU_223 is offline Offline
Newbie Poster

perl loop problem (from a beginner)

 
0
  #1
May 7th, 2009
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";
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 898
Reputation: KevinADC has a spectacular aura about KevinADC has a spectacular aura about 
Solved Threads: 67
KevinADC's Avatar
KevinADC KevinADC is offline Offline
Practically a Posting Shark

Re: perl loop problem (from a beginner)

 
0
  #2
May 7th, 2009
"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:

  1. use warnings;
  2. use strict;
  3. my @list;
  4. print "Enter number of OTUs:";
  5. my $start = <STDIN>;
  6. chomp $start;
  7. do {
  8. my $rand = int(rand($start));
  9. print "rand = $rand\n";
  10. push (@list, $rand);
  11. $start-=$rand;
  12. print "\$start = $start\n";
  13. } until ($start == 0);
  14.  
  15. print "@list";
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 7
Reputation: LSU_223 is an unknown quantity at this point 
Solved Threads: 0
LSU_223 LSU_223 is offline Offline
Newbie Poster

Re: perl loop problem (from a beginner)

 
0
  #3
May 8th, 2009
Thanks!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Perl Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC