in reply to Select randomly from a hash

What's wrong with:

%verbs = {"jumped","eat","killed"}; %pronouns = {"I","You","He","She"}; my @pronouns = shuffle keys %pronouns; foreach my $verb (shuffle keys %verbs) { print shift(@pronouns), ' ', $verb, "\n"; @pronouns = shuffle keys %pronouns if (scalar(@pronouns) == 0); }

Replies are listed 'Best First'.
Re^2: Select randomly from a hash
by Fletch (Bishop) on Oct 17, 2004 at 01:35 UTC

    Well, for one thing { } is the anonymous hashref constructor and you'd get an odd-number-of-elements-in-hash-assignement warning. And for another you left off use List::Util qw( shuffle ).

Re^2: Select randomly from a hash
by davido (Cardinal) on Oct 17, 2004 at 03:50 UTC

    The keys of %verbs are "jumped" and "killed". The values associated with those keys are "eat" and undef.

    The keys of %pronouns are "I", and "He". The values associated with those keys are "You" and "She".

    So you're shuffling two pronouns, not four, and two verbs, not four. So the only possible pronouns, given your code, will be "I" and "He". "She" and "You" will never be selected. Bummer for you and her. ;)

    And with your code (assuming you fixed the missing List::Utils, and uneven key/value pairs), the only actions that He and I could perform would be jumped and killed. ...we would never eat.


    Dave