Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: How to sort the data in Array which has format MMYY

by sundialsvc4 (Abbot)
on Jul 02, 2013 at 14:14 UTC ( #1042019=note: print w/ replies, xml ) Need Help??


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

As you know, the sort verb takes as one argument a subroutine (or an in-line block of code) whose job it is to return a value that is less than, equal to, or greater than zero when given two keys to compare.   It can be a separate subroutine, and I like to do it that way, especially when I have several occurrences of the same sort.

When dealing with date-values, I prefer to use a nice “date/time object” such as DateTime, which relieves me of all concerns about date/time handling.

But, when you can’t do that, you can do sorting of months by defining a hashref that gives you numeric equivalents for them.   So, your sorting subroutine becomes something like this:   (untested)

my %month_sort = ( 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, ... etcetera ... ); sub sort_cmp { my ($a, $b) = @_; return ( substr($a, 3, 2) cmp substr($b, 3, 2) ) || ( $month_sort->{substr($a, 0, 3)} <=> $month_sort->{substr($b, 0, 3)} ); }


Comment on Re: How to sort the data in Array which has format MMYY
Download Code
Replies are listed 'Best First'.
Re^2: How to sort the data in Array which has format MMYY
by Anonymous Monk on Jul 02, 2013 at 15:04 UTC

    Maybe when replying to somebody who already says is new to perl, it would be nice to actually test your code.

    Problems:

    1) don't pass $a and $b to a sort sub, since they are special variables

    2) don't treat a hash like a hashref, it just won't work

    3) you don't need the return either

    This does work:
    use strict; use warnings; my %month_sort = ( 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12 ); sub sort_cmp { ( substr($a, 3, 2) cmp substr($b, 3, 2) ) || ( $month_sort{substr($a, 0, 3)} <=> $month_sort{substr($b, 0, 3)} ); } my (@months) = qw(APR12 MAR13 APR11 MAR12 FEB13 APR13); @months = ( sort sort_cmp @months); print "@months \n";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1042019]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2015-07-29 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (269 votes), past polls