Alexander Farber Alexander Farber - 2 months ago 5
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


Somewhat more concise:

my $random_value = $hash{(keys %hash)[rand keys %hash]};