954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Restrict random numbers genrated by rand()

I am trying to use the rand function to generate numbers from an array containing 3 ranges. This is unfortunately not working. I know I am doing something wrong, either with rand() or with my array declaration. Can someone please correct me:

my @numbers = [48..57, 97..112, 65..90];

$num = int(rand(@numbers));
sid78669
Junior Poster
198 posts since Nov 2008
Reputation Points: 10
Solved Threads: 8
 
Rashakil Fol
Super Senior Demiposter
Team Colleague
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
 

The problem is you are generating a random number based on the length of the array, not the values of the elements of the array. Here is what you want to do:

my @numbers = (48..57, 65..90, 97..112);
my $num = $numbers[int rand @numbers];
print $num,"\n";
KevinADC
Posting Shark
921 posts since Mar 2006
Reputation Points: 246
Solved Threads: 67
 

That's not how rand works:

http://perldoc.perl.org/functions/rand.html

Hes just not applying it correctly to this particular problem.

KevinADC
Posting Shark
921 posts since Mar 2006
Reputation Points: 246
Solved Threads: 67
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You