[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Pick a random array element ... beware the web experts :)



This is a great little explanation I hit Googling for how to pick a
random array element today:

http://www.webmasterworld.com/forum13/668.htm

Except.... at the end when he shows the one liner:

#now all together
@a = ($text1,$text2,$text3,...,'unused element');
print $a[int rand($#a)]; 

It's wrong. The correct print statement is:

print $a[int rand($#a + 1)]; 

because $#a is not the number of elements, its the highest index of @a.



Here's the bug demo'd:

$ cat j2.pl
my @a = ("X", "Y");
for (1..50) {
  print $a[ int rand($#a) ];
}
print "\n";
for (1..50) {
  print $a[ int rand($#a + 1) ];
}
print "\n";

$ perl j2.pl
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XYXYYXXYYXXXXYYXXXYXXYYXXXYYYYXYYXXYYXYXXYYXXYXYYX



Oops. Beware the experts*.  :)

j
* and emails from me. >:)