[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Sort quickie




I had a bunch of hash keys that were dates in MMDDYYYY format. I wanted to get a sorted list of the keys. Perl to the rescue! Have y'all configured custom sort subroutines before? They're cool...

The real code in context...
------------
   print "\n\nGroup pickup by cap_date (running total):\n";
   foreach (sort sort_by_cap_date keys %{$group_pickup{by_cap_date}}) {
      my $val = $group_pickup{by_cap_date}{$_};
      next if $val == 0;
      print "$_: $val\n";
   }
}

sub sort_by_cap_date ($$) {
# We have to throw some mojo here since capdate is MMDDYYYY and obviously
   # we can't sort until we turn it into YYYYMMDD... -jhannah 6/14/04
   my ($a, $b) = @_;
   for ($a, $b) {
      s/(\d\d)(\d\d)(\d\d\d\d)/$3$1$2/;
   }
   $a <=> $b;
}
---------------

Same idea, distilled out to see the results easier and so you can play with it:
---------------
my @dates = qw( 05012003 02012004 11012002 );
print join ", ", sort @dates;
print "\n";
print join ", ", sort by_date @dates;
print "\n";

sub by_date ($$) {
   my ($a, $b) = @_;
   for ($a, $b) {
      s/(\d\d)(\d\d)(\d\d\d\d)/$3$1$2/;
   }
   $a <=> $b;
}
----------------

"sort" just does an ASCII sort, which isn't in date order for MMDDYYYY dates. Instead, "sort by_date" does a comparison after converting MMDDYYYY into YYYYMMDD, which does sort dates correctly. It doesn't munge the real values though.

Neat, huh?

perldoc -f sort

j