Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a random key from a hash

Tags:

perl

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. like this:

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

I wonder if it's the correct way or if there is a better way.

like image 508
Alexander Farber Avatar asked Dec 17 '11 20:12

Alexander Farber


1 Answers

Somewhat more concise:

my $random_value = $hash{(keys %hash)[rand keys %hash]};
like image 51
ennuikiller Avatar answered Sep 18 '22 18:09

ennuikiller