Selecting a random key from a hash

后端 未结 3 1865
萌比男神i
萌比男神i 2021-02-19 03:43

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:

3条回答
  •  心在旅途
    2021-02-19 04:23

    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;
    }
    

提交回复
热议问题