in reply to Select randomly from a hash
The fact that it looks more like you should be using an array notwithstanding, I'll go ahead and answer the question asked in the subject line anyway:
Here is one way to select a single random element from a hash:
my $randelement = ( keys %hash )[ rand( scalar keys %hash ) ];
This works by creating a list of the keys, and then by generating a random number between zero and n, where n is the number of keys. Using keys in scalar context is an efficient way of determing the number of keys in the hash. That random number is then used as a list index (like an array index) to grab the element corresponding with that random index number. The fact that rand generates floating point numbers doesn't matter; array and list indices are implicitly truncated to integers. That also means that 10.999 will be the element number 10, which is the 11th element. And 0.999 will be element number 0, the 1st element.
If you're going to be grabbing several elements, and don't want to repeat, use a Fisher Yates shuffle, from List::Utils and then iterate over the list.
Dave
|
---|