View Single Post
  #4 (permalink)  
Old March 10th, 2007, 07:46 AM
ciderpunx ciderpunx is offline
Friend of Wrox
Points: 1,515, Level: 15
Points: 1,515, Level: 15 Points: 1,515, Level: 15 Points: 1,515, Level: 15
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Dec 2003
Location: Oxford, , United Kingdom.
Posts: 488
Thanks: 0
Thanked 3 Times in 3 Posts
Default

ah ok,

Well, if they were the other way round you could just order them as strings - i.e. 2007-4-9 comes after 2007-4-2 in the alphabet. In the following code there is a subroutine to swap the field ordering (reverse_date()). We then use the block form of the sort function to string compare the two dates with their fields reversed.

Code:
#!/usr/bin/perl
use warnings;
use strict;

sub reverse_date($) {
  my $date_to_reverse = shift;
  my @swap = split /-/,$date_to_reverse;
  return join '-',reverse @swap;
}

my $first_date = "9-4-2007";
my $second_date = "2-4-2007";

my ($earlier,$later) = sort {reverse_date($a) cmp reverse_date($b)} $first_date, $second_date;
print "Earlier date: $earlier\nLater date: $later\n";
On my computer this does:

Code:
charlie@mogadon:~$ ./tmp.pl
Earlier date: 2-4-2007
Later date: 9-4-2007
charlie@mogadon:~$
HTH

--
Charlie Harvey's website - linux, perl, java, anarchism and punk rock: http://charlieharvey.org.uk