http://qs321.pair.com?node_id=1870

vroom has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How do I pick a random element from an array?

Originally posted as a Categorized Question.

  • Comment on How do I pick a random element from an array?

Replies are listed 'Best First'.
Re: How do I pick a random element from an array?
by vroom (His Eminence) on Jan 09, 2000 at 10:09 UTC
    $randomelement = $array[rand @array];
Re: How do I pick a random element from an array?
by LEFant (Scribe) on Sep 11, 2002 at 04:01 UTC
    The alternative answer provided by rajib will indeed provide a random element from an array but a biased one. Since rand $#array returns a real greater than or equal to 0 and less than the maximum index of the array the maximum index itself will never be returned. Perl truncates the fractional part of the real rather than rounding to yield the integer index. Use the first solution, contributed by vroom, with rand $array to include the last element in the sample population.

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.