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?

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;
@hash{@keys}=@values;

@keys = shuffle(@keys);
for(@keys){
    print "$hash{$_}\n";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.