Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a hash as follows -
my %verb = ( 'To Move' => 'Zegi', 'To Break' => 'Loga', 'To Think' => 'Fzetra', );
This would print the hash in order -
foreach my $verb (sort keys %verb) { print $verb; }
How would I print it randomly every time?

Replies are listed 'Best First'.
Re: Randomize a Hash
by BrowserUk (Patriarch) on Oct 16, 2004 at 19:00 UTC
    use List::Util qw[ shuffle ]; my %verb = ( 'To Move' => 'Zegi', 'To Break' => 'Loga', 'To Think' => 'Fzetra', ); This would print the hash in order - foreach my $verb (shuffle keys %verb) { print $verb; }

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re: Randomize a Hash
by TedPride (Priest) on Oct 16, 2004 at 20:14 UTC
    use strict; use warnings; my ($rand, $c); my %verb = ( 'To Move' => 'Zegi', 'To Break' => 'Loga', 'To Think' => 'Fzetra', ); for (0..20) { my @arr = (keys %verb); for ($c = @arr; --$c;) { my $rand = int rand ($c+1); @arr[$c,$rand] = @arr[$rand,$c]; } print join(' ', @arr) . "\n"; }
    This randomizes the keys using the Fisher-Yates Shuffle and prints them. Note that you can also print using the following statements if you prefer:
    print (map(($_, ' '), @arr), "\n"); print $_ . " " for (@arr); print "\n";