in reply to How to sort the data in Array which has format MMYY

Firstly, the months in your hash lookup are mixed case, while in your data they're uppercase. Hash keys are case sensitive.

Secondly, in your by_month function you're getting strings like "APR12" and looking them up in a hash with keys like "Apr". You need to strip the number off before looking them up in the hash.

Here's a fixed version of your script:

#!/usr/bin/env perl my (@months) = qw(APR12 MAR13 APR11 MAR12 FEB13 APR13); my @mon = map uc, qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec +); my $mon; @{$mon}{@mon} = ( 0 .. $#mon ); sub by_month { my ($a_mon, $a_yy) = ($a =~ /(...)(..)/); my ($b_mon, $b_yy) = ($b =~ /(...)(..)/); $mon->{$a_mon} <=> $mon->{$b_mon}; } @months = ( sort by_month @months ); print "@months\n";

Note that the above completely ignores the years though. If you want to sort by year first and then month, you could use:

#!/usr/bin/env perl my (@months) = qw(APR12 MAR13 APR11 MAR12 FEB13 APR13); my @mon = map uc, qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec +); my $mon; @{$mon}{@mon} = ( 0 .. $#mon ); sub by_month { my ($a_mon, $a_yy) = ($a =~ /(...)(..)/); my ($b_mon, $b_yy) = ($b =~ /(...)(..)/); $a_yy <=> $b_yy or $mon->{$a_mon} <=> $mon->{$b_mon}; } @months = ( sort by_month @months ); print "@months\n";

If you've got a lot of data, the speed could be improved via a Schwartzian transform, but as you're new to Perl, I won't get into that. ;-)

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: How to sort the data in Array which has format MMYY
by BillKSmith (Monsignor) on Jul 02, 2013 at 11:05 UTC
    Refer to the FAQ perldoc -q "How do I sort an array" for details on Schwartzian Transform.
    Bill
Re^2: How to sort the data in Array which has format MMYY
by kum@12 (Initiate) on Jul 03, 2013 at 15:19 UTC
    Hi All,

    When i try to sort the input data, i am not getting the wrong results

    #!/usr/bin/env perl my (@months) = qw(Mar13 Jun13 Jul13 Apr13 ); my @mon = map uc, qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec +); my $mon; @{$mon}{@mon} = ( 0 .. $#mon ); sub by_month { my ($a_mon, $a_yy) = ($a =~ /(...)(..)/); my ($b_mon, $b_yy) = ($b =~ /(...)(..)/); $a_yy <=> $b_yy or $mon->{$a_mon} <=> $mon->{$b_mon}; } @months = ( sort by_month @months ); print "@months\n";

    output

    Mar13 Jun13 Jul13 Apr13

    please help me on this</P<

      If your @months are no longer upper case, drop the uc.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ