943,811 Members | Top Members by Rank

Ad:
  • Perl Discussion Thread
  • Unsolved
  • Views: 866
  • Perl RSS
May 7th, 2009
0

perl loop problem (from a beginner)

Expand Post »
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";
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
LSU_223 is offline Offline
7 posts
since Apr 2009
May 7th, 2009
0

Re: perl loop problem (from a beginner)

"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)
  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";
Reputation Points: 246
Solved Threads: 67
Practically a Posting Shark
KevinADC is offline Offline
898 posts
since Mar 2006
May 8th, 2009
0

Re: perl loop problem (from a beginner)

Thanks!
Reputation Points: 10
Solved Threads: 0
Newbie Poster
LSU_223 is offline Offline
7 posts
since Apr 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Perl Forum Timeline: Dynamic Array
Next Thread in Perl Forum Timeline: Help! comparing two sequences through perl





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC