943,623 Members | Top Members by Rank

Ad:
  • Perl Discussion Thread
  • Marked Solved
  • Views: 1323
  • Perl RSS
Jul 31st, 2009
0

Randomize Hash Iteration

Expand Post »
I have been using this code:
perl Syntax (Toggle Plain Text)
  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:
perl Syntax (Toggle Plain Text)
  1. $x = int(rand(14)); #assuming the array has 15 elements
  2. print "$array[$x]";
Is there anything like that for hashes?
Similar Threads
Reputation Points: 17
Solved Threads: 5
Junior Poster
orwell84 is offline Offline
100 posts
since Nov 2008
Jul 31st, 2009
0

Re: Randomize Hash Iteration

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:

perl Syntax (Toggle Plain Text)
  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.
Reputation Points: 246
Solved Threads: 67
Practically a Posting Shark
KevinADC is offline Offline
898 posts
since Mar 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Perl Forum Timeline: Perl Script
Next Thread in Perl Forum Timeline: Backreference Variables





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC