I have been using this code:

while (($key, $value) = each (%hash))

To iterate through a hash. However, the order of the keys that it retrieves are exactly the same each time i run the script. I looked to google for answers and found the following bug report. From other sources, it seems that this is normal.
Are there any workarounds to make the order random? With an array, I would probably just do this:

$x = int(rand(14));  #assuming the array has 15 elements
print "$array[$x]";

Is there anything like that for hashes?

7 Years
Discussion Span
Last Post by KevinADC

hashes are not randomly ordered lists, they are lists that don't have any guaranteed ordered, but they should always be the same order on the same computer. So that bug report appears to be erroneous because the reporter did not seem to understand that hashes are not randomly ordered.

If you need to use a hash, you can store the keys in an array and use List::Util and the shuffle function to randomly order the array with the hash keys. Then loop over the array instead of the hash. An example:

use List::Util qw/shuffle/;
my @keys = (1..26);
my @values = ('a'..'z');
my %hash;

@keys = shuffle(@keys);
    print "$hash{$_}\n";
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.