I have stolen ikegama's idea of using map along with aquarium's idea of reordering the date so it sorts easily and come up with the following little snippet. The date is re-ordered in the map block and munged together with the key to make it easy to sort the entire thing as an array. once sorted it is easy to reconstruct the data as you like.

This does depend on the day, date and year being 2,2,4 digits, if they are not then a little more needs adding in the map block to fix this

cheers.

#!/usr/local/bin/perl -w use strict; my %h = ( key1 => "10/14/2003", key2 => "11/23/2001", key3 => "12/23/2001", key4 => "12/22/2001", key5 => "02/21/1984", key6 => "08/13/1969", key7 => "09/11/1973", key8 => "09/30/2000" ); my @bydate = map { my @tmp = split /\//, $h{$_}; $tmp[2].":".$tmp[0].":".$tmp[1].":".$_ } keys(%h); foreach (sort @bydate) { my ($yr, $mn, $dy, $key) = split /:/; print "$mn/$dy/$yr = $key\n"; }

update
I have been playing with pack/unpack and thought this was a nice place to use it. So here is a more efficient version
#!/usr/local/bin/perl -w use strict; my %h = ( key1 => "10/14/2003", key2 => "11/23/2001", key3 => "12/23/2001", key4 => "12/22/2001", key5 => "02/21/1984", key6 => "08/13/1969", key7 => "09/11/1973", key8 => "09/30/2000" ); my @bydate = map { my @tmp = split /\//, $h{$_}; pack 'A4A2A2A*', $tmp[2], $tmp[0], $tmp[1], $_; } keys(%h); foreach (sort @bydate) { print "@{[unpack ('A4A2A2A*',$_)]}\n"; }

In reply to Re: sorting a hash by its values, date by Random_Walk
in thread sorting a hash by its values, date by levbao

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.