I have a hash of arrays that I want to loop through. That's easy enough. However, I want to loop through them in a specific order - or only partly a specific order. If a certain key exists (no guarantee here), I want that one to be done first. Otherwise order doesn't matter.

What is the smallest, most readable, or preferably both, way to approach this? If I could guarantee that the key exists, I would do something like:

for my $key ('Foo', grep { $_ ne 'Foo' } keys %HoA) { ... }
Checking for Foo's existance seems a bit cumbersome:
for my $key ( exists $HoA{Foo} ? ('Foo') : (), grep { $_ ne 'Foo' } keys %HoA ) { ... }
Is there a simpler way to look at this that I'm missing?

PS: For simplicity, imagine the %HoA has the keys qw(D E F Foo G H). The order I deal with D E F G and H should not be touched from the hash ordering if I can help it.

Update: FYI: The only reason I want to avoid touching the hash ordering is because I don't want to rely on their ordering. It's not because I'm relying on it, but precisely the opposite - keys is supposed to return a differing order from run to run. I want to take advantage of that precisely by being able to show that my algorithm doesn't depend on order except for 'Foo'.

I'm also not looking for optimisation from the perspective of CPU cycles. I'm looking for something that is short, sweet, to the point, and, most importantly, blatantly obvious as to what I'm trying to do.

And, yes, some of the responses have given me other ways to think about it (including tye's anony-sub WTDI). Thanks!


In reply to Pulling an item to the front of the list by Tanktalus

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.