Front page | perl.macosx | Postings from March 2005

## Re: Sorting year and month

From:
John Horner
Date:
March 1, 2005 21:14
Subject:
Re: Sorting year and month
Message ID:
a06110401be4af9844d2f@[10.25.230.138]
```I was interested by this question -- and let me say, of course the
correct answer is, "use the module" -- I just took the opportunity to

The following is of course a very roundabout solution, but it shows
how you can sort by an arbitrary quality you assign yourself (as you
might if you wanted to sort the months from financial year to
financial year where April might be 1 and March 12) and how to
sub-sort.

#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use Data::Dumper;

my %months = ( Jan => 1, Feb => 2, Mar => 3, Apr => 4 );
## Assign values to the month names,
## I'm too lazy to do the whole 12.

my @dates = qw(
Apr-2005 Feb-2001 Mar-2001
Jan-2004 Jan-2005 Mar-2005
Feb-2003 Mar-2003 Apr-2003
Mar-1999 Apr-1999 Feb-2002
);
## randomly chosen dates in random order

my @data = ();

for ( @dates ) {
my ( \$m, \$y ) = split( '-', \$_ );
push( @data, { year => \$y, month => \$m } );
}
## build AoH from dates

@data = sort {
\$a->{year} <=> \$b->{year}
||
\$months{ \$a->{month} } <=> \$months{ \$b->{month} }
} @data;

## only if the years are equal does the second sort take place, is that right?

print Dumper( \@data );

## seems to work:

# \$VAR1 = [
#           {
#             'month' => 'Mar',
#             'year' => 1999
#           },
#           {
#             'month' => 'Apr',
#             'year' => 1999
#           },
#           {
#             'month' => 'Feb',
#             'year' => 2001
#           },
#           {
#             'month' => 'Mar',
#             'year' => 2001
#           },
#           {
#             'month' => 'Feb',
#             'year' => 2002
#           },
#           {
#             'month' => 'Feb',
#             'year' => 2003
#           },
#           {
#             'month' => 'Mar',
#             'year' => 2003
#           },
#           {
#             'month' => 'Apr',
#             'year' => 2003
#           },
#           {
#             'month' => 'Jan',
#             'year' => 2004
#           },
#           {
#             'month' => 'Jan',
#             'year' => 2005
#           },
#           {
#             'month' => 'Mar',
#             'year' => 2005
#           },
#           {
#             'month' => 'Apr',
#             'year' => 2005
#           }
#         ];
#

```