The code below is less elegant than others in this thread. I understand qw// better now...
However, I do attempt to use the supplied sample data, account for 1 or 2 digit months and days and puke if I don't get a 4 digit year.
#!/usr/bin/perl -w
use strict;
my @test=( "example: 10/29/2001",
"example: 2/18/2000 3rd quarter",
"example: 3/18/2000 4th quarter",
"example: 4/18/2000 4th quarter",
"example: 5/18/2000 4th quarter",
"example: 6/18/2000 1st quarter",
"example: 7/18/2000 1st quarter",
"example: 11/18/2001 2nd quarter",
"example: 01/18/1999 3rd quarter",
"example: 02/18/1999 3rd quarter",
"example: 3/18/1999 4th quarter",
"example: 4/18/1999 4th quarter",
"example: 5/18/1999 4th quarter",
"example: 6/18/1999 1 quarter",
"example: 7/18/1999 1 quarter",
"example: 8/18/1999 1 quarter",
"example: 9/18/1999 2nd quarter",
"example: 10/18/1999 2nd quarter",
"example: 11/18/1999 2nd quarter",
"example: 12/18/1999 3rd quarter"
);
sub my_compare(){
# use "our" to limit scope to function but persist
# map months to quarters
our %quarters=(
'6'=> 1,
'06'=> 1,
'7'=> 1,
'07'=> 1,
'8'=> 1,
'08'=> 1,
'9'=> 2,
'09'=> 2,
'10'=> 2,
'11'=> 2,
'12'=> 3,
'1'=> 3,
'01'=> 3,
'2'=> 3,
'02'=> 3,
'3'=> 4,
'03'=> 4,
'4'=> 4,
'04'=> 4,
'5'=> 4,
'05'=> 4
);
# $a and $b are given to us by sort
# they are the left & right sides of the comparision
#
my ($mon, $day);
$a=~m|(\d*)/(\d*)/(\d*)|;
$mon=length($1)<2?'0'.$1:$1;
$day=length($2)<2?'0'.$2:$2;
my $a3=$3 . $quarters{$mon}.$mon .$day;
die "bad year in $a" unless length ($3)==4;
$b=~m|(\d*)/(\d*)/(\d*)|;
$mon=length($1)<2?'0'.$1:$1;
$day=length($2)<2?'0'.$2:$2;
my $b3=$3 . $quarters{$mon}. $mon .$day;
die "bad year in $b" unless length ($3)==4;
return $a3 <=> $b3;
}
@test=sort(my_compare(), @test);
print join "\n", @test;
--mandog
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.