Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

How do I pick a random element from an array?

by vroom (His Eminence)
on Jan 08, 2000 at 08:19 UTC ( [id://1870]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1870]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-07-16 20:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.