Alexander Farber Alexander Farber - 1 year ago 122
Perl Question

Select a random hash key

How do you select a random hash key?

For my Flash+Perl card game I'm trying to pick a random card from a hash where keys are: "6 spades", "6 clubs", etc.:

my $card;
my $i = 0;
for $card (keys %{$user->{HAND}}) {
last if rand(++$i) < 1;
delete $user->{HAND}->{$card};
print "random card: $card\n";

and wonder if it's correct at all and if there is a better way

Answer Source

Somewhat more concise:

my $random_value = $hash{(keys %hash)[rand keys %hash]};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download