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));

Recommended Answers

All 3 Replies

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";
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.