Randomize Hash Iteration

Thread Solved

Join Date: Nov 2008
Posts: 70
Reputation: orwell84 is an unknown quantity at this point 
Solved Threads: 3
orwell84's Avatar
orwell84 orwell84 is offline Offline
Junior Poster in Training

Randomize Hash Iteration

 
0
  #1
Jul 31st, 2009
I have been using this code:
  1. 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:
  1. $x = int(rand(14)); #assuming the array has 15 elements
  2. print "$array[$x]";
Is there anything like that for hashes?
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 898
Reputation: KevinADC has a spectacular aura about KevinADC has a spectacular aura about 
Solved Threads: 67
KevinADC's Avatar
KevinADC KevinADC is offline Offline
Practically a Posting Shark

Re: Randomize Hash Iteration

 
0
  #2
Jul 31st, 2009
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:

  1. use List::Util qw/shuffle/;
  2. my @keys = (1..26);
  3. my @values = ('a'..'z');
  4. my %hash;
  5. @hash{@keys}=@values;
  6.  
  7. @keys = shuffle(@keys);
  8. for(@keys){
  9. print "$hash{$_}\n";
  10. }
Last edited by KevinADC; Jul 31st, 2009 at 3:52 pm.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC