The previous replies address and correct a problem with the data format in the OP. This reply addresses a question of style.

Since the intent seems to be to do a multi-key sort (first by date, then by time and then by hash key), this intent is more clearly and maintainably implemented by sorting in just this way.

Although the main benefit is clarity, there may also be a side-benefit of better performance, since the relatively expensive (as well as messy) arithmetic operations are not needed for each comparison of the sort.

If performance is really an issue due to hash size, a ST or GRT approach may be merited. See A Fresh Look at Efficient Perl Sorting and also Old sorting paper holds the key to unlocking the secrets of the Schwartzian Transform for a discussion of and general comments on both approaches.

Sort by combined date-time, then key:

>perl -wMstrict -le "my %HoA = ( 2 => ['cd', 20090101, 91010], 3 => ['ef', 20090201, 101000], 1 => ['ab', 20090101, 91010], ); my @ordered_keys = sort { ($HoA{$a}[1]*1000000+$HoA{$a}[2]) <=> ($HoA{$b}[1]*1000000+$HoA{$ +b}[2]) || $a <=> $b } keys (%HoA); for my $key (@ordered_keys) { print qq{$key -> [@{$HoA{$key}}]} } " 1 -> [ab 20090101 91010] 2 -> [cd 20090101 91010] 3 -> [ef 20090201 101000]
Sort explicitly by date, time, key:
>perl -wMstrict -le "my %HoA = ( 2 => ['cd', 20090101, 91010], 3 => ['ef', 20090201, 101000], 1 => ['ab', 20090101, 91010], ); my @ordered_keys = sort { $HoA{$a}[1] <=> $HoA{$b}[1] || $HoA{$a}[2] <=> $HoA{$b}[2] || $a <=> $b } keys %HoA; for my $key (@ordered_keys) { print qq{$key -> [@{$HoA{$key}}]} } " 1 -> [ab 20090101 91010] 2 -> [cd 20090101 91010] 3 -> [ef 20090201 101000]

In reply to Re: sort HoA by tow keys by AnomalousMonk
in thread sort HoA by tow keys by jiwei800715

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.