如何选择随机哈希键?对于my Flash+Perl card game我试图从哈希中选择一张随机牌,其中键是:“6个黑桃”,“6个俱乐部”等,如下所示:
my $card;
my $i = 0;
for $card (keys %{$user->{HAND}}) {
last if rand(++$i) < 1;
}
delete $user->{HAND}->{$card};
print "random card: $card\n";
我想知道这是正确的方式还是有更好的方式。
答案 0 :(得分:17)
更简洁:
my $random_value = $hash{(keys %hash)[rand keys %hash]};
答案 1 :(得分:14)
%hash
的密钥存储在@hash_keys
。0
与@hash_keys
@hash_keys
%hash
示例代码段:
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
答案 2 :(得分:1)
这是另一种方式(演示如何从未知长度列表中选择随机元素):
my $cards;
my $chosen;
while ( my $card = each %{$user->{HAND}} ) {
$chosen = $card if rand(++$cards) < 1;
}