in reply to Re: sorting keys in hash
in thread sorting keys in hash

Hi,

I want the output in MMMYY format, the present output is alphabetically sorted but I am trying to print output in MMMYY format sorted way

Expected Output:

key - Dec13 and value - 2 key - Mar14 and value - 2 key - Apr14 and value - 2 key - May14 and value - 2

Replies are listed 'Best First'.
Re^3: sorting keys in hash
by kennethk (Abbot) on May 23, 2014 at 16:17 UTC
    So that means you must write your own comparison subroutine, as described in sort. You'll also need to specify ordering on months, since MMM format doesn't naturally sort. Something like:
    my %MMM_order = ( Mar => 3, Apr => 4, May => 5, Dec => 12, ); sub cmp_MMMYY { my ($a_mon, $a_yr) = $a =~ /(.{3})(\d{2})/; my ($b_mon, $b_yr) = $b =~ /(.{3})(\d{2})/; $a_yr cmp $b_yr or $MMM_order{$a_mon} <=> $MMM_order{$b_mon}; }

    Given the content of your post convert date format from YYYY-MM-DD to YYYYMMDD, I should mention that this sort would be much more natural in ISO 8601, and there are conversion methods discussed in the response to that post.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re^3: sorting keys in hash
by LanX (Saint) on May 23, 2014 at 16:10 UTC
    You are only repeating not explaining. :(

    I'm out! :)

    update

    If 13 means the year and not the day this could be indeed chronological. (?)

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      horrible data structure ... :(

      use warnings; use strict; use Data::Dump; my @unsorted =qw( Dec02 Jan02 May05 Dec01 Apr05 May15 ); my @sorted= sort datesort @unsorted; dd \@unsorted,\@sorted; my @months= qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); my %month_order; @month_order{@months} = 1..12; #dd \%month_order; sub datesort { my ($am,$ay) = $a =~ /(\w\w\w)(\d\d)/; my ($bm,$by) = $b =~ /(\w\w\w)(\d\d)/; return $ay <=> $by or $month_order{$am} <=> $month_order{$bm}; }

      Cheers Rolf

      ( addicted to the Perl Programming Language)

      Hi,

      As I mentioned I don't want to display the output in alphabetic order, need to display the output as sorted months if key is MAR14 --> 02,MAY14 --> 02,APR14,DEC13--> 02 --> 02

      expecting the output in sorted months as DEC13--> 02,MAR14 --> 02,APR14-->,MAY14 --> 02

      Thanks J