in reply to Pulling random elements from hash

You'd probably be better served by an array for this, where you could just do:
$array[int(rand(scalar(@array)))];
to choose a random element.

You can do much the same thing, though, by pulling the hash keys into a list and choosing one randomly:

$hk = (keys %hash)[int(rand(scalar(keys %hash)))]; $hv = $hash{$hk};
If you'll do it often, pull the keys into an array and just use that:
@arr = keys %hash; $hk = $arr[int(rand(scalar(@arr)))]; $hv = $hash{$hk};

With both of the hash solutions, you end up with two copies of all the keys, so it's less memory-efficient than an array, but probably fine if you have a few thousand entries or less.

Replies are listed 'Best First'.
Re^2: Pulling random elements from hash
by Aristotle (Chancellor) on Jun 22, 2003 at 02:00 UTC
    $array[int(rand(scalar(@array)))];
    Of course you can just write
    $array[rand @array];
    which will do exactly the same thing and is a bit less distracting to read.

    Makeshifts last the longest.

      I saw that in another post. Do you know why this is? It seems like rand is unlikely to pick an integer, and $array[3.14159] seems nonsensical, but I tried it and it works...