If you don't mind throwing a little memory at it, you could do it this way, and still preserve the usefulness of the original hash.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.