| | |
Randomize Hash Iteration
Thread Solved |
I have been using this code:
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:
Is there anything like that for hashes?
perl Syntax (Toggle Plain Text)
while (($key, $value) = each (%hash))
Are there any workarounds to make the order random? With an array, I would probably just do this:
perl Syntax (Toggle Plain Text)
$x = int(rand(14)); #assuming the array has 15 elements print "$array[$x]";
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:
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)
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"; }
Last edited by KevinADC; Jul 31st, 2009 at 3:52 pm.
![]() |
Similar Threads
- Reading txt file into Hash Table (C++)
- Linked List help (C++)
- hash- linear probing (C)
- Randomize number with OpenGL (C++)
- Printing a Hash Table (C++)
- Recursive Hash map - unhandled exception help (C)
- Pass XML file contents to a hash table. (Java)
- compile error-chained hash table c++ (C++)
- Help with iteration in 'while' loop (C++)
Other Threads in the Perl Forum
- Previous Thread: Perl Script
- Next Thread: Backreference Variables
| Thread Tools | Search this Thread |





