in reply to Pulling random elements from hash
to choose a random element.$array[int(rand(scalar(@array)))];
You can do much the same thing, though, by pulling the hash keys into a list and choosing one randomly:
If you'll do it often, pull the keys into an array and just use that:$hk = (keys %hash)[int(rand(scalar(keys %hash)))]; $hv = $hash{$hk};
@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 | |
by sgifford (Prior) on Jun 22, 2003 at 02:15 UTC | |
by merlyn (Sage) on Jun 22, 2003 at 02:45 UTC |