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:
%hash
in @hash_keys
.0
and the length of @hash_keys
@hash_keys
%hash
Example snippet:
my %hash = (
'stack' => 'overflow',
'face' => 'book',
'inter' => 'net'
);
## ALTERNATIVE 1 ##
my @hash_keys = keys %hash;
my $random_key = $hash_keys[rand @hash_keys];
my $random_value = $hash{$random_key};
## ALTERNATIVE 2 ##
my $random_val_2 = (%hash)[1+2*int rand keys%hash]; # TIMTOWTDI
## ALTERNATIVE 3 ##
my $random_val_3 = [@_=%hash]->[1|rand@_]; # TIMTOWTDI
Here's another way (demonstrating how to pick a random element from a list of unknown length):
my $cards;
my $chosen;
while ( my $card = each %{$user->{HAND}} ) {
$chosen = $card if rand(++$cards) < 1;
}
Somewhat more concise:
my $random_value = $hash{(keys %hash)[rand keys %hash]};