my @keybucket = keys %db; shuffle (@keybucket); foreach my $key ( @keybucket ) { print qq(<a href = "$key"><img src="/images/$db{$key}"</a>); }
I took some liberties with the general flow and variable names used in this snippet. You'll have to massage it to fit your needs. But the idea is why coerce the hash into an array of unnatural character when you can keep the hash and just make a shuffled list of its keys.
This approach has merit in a situation where you want to ensure that you are holding the entire shuffled deck, so to speak, so that you can guarantee uniqueness as you draw additional items from it. If you're only interested in one random item, the creation and shuffling of an array is overkill. However, if you want to draw multiple random items, and make sure not to draw the same one twice, the array of hash keys approach is good because you can just keep shifting items off the top of the stack one by one, or even take an array slice of the stack if you need multiple items.
If you use such an approach (to solve this or other problems) you should take care to always update the array of keys if you've added another item to the hash.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
In reply to Re: converting hash to shuffled array
by davido
in thread converting hash to shuffled array
by sulfericacid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |