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.
Somewhat more concise:
my $random_value = $hash{(keys %hash)[rand keys %hash]};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With