use strict; use warnings; use Benchmark qw(cmpthese); # Generate a thousand dates at random. # my @startDates; push @startDates, sprintf(q{%02d}, int((rand 28) + 1)) . q{-} . sprintf(q{%02d}, int((rand 12) + 1)) . q{-} . int((rand 25) + 2000) for (1 .. 1000); # cog's method. # my $rcCog = sub { my @sortedDates = map { $_->{date} } sort { $a->{year} <=> $b->{year} or $a->{month} <=> $b->{month} or $a->{day} <=> $b->{day} } map { /(\d\d)-(\d\d)-(\d\d\d\d)/; { date => $_, day => $1, month => $2, year => $3 } } @startDates; return $sortedDates[0]; }; # JediWizard's method. # my $rcJediWizard = sub { my %dateHash = (); my @sortedDates = sort { ($dateHash{$a} ||= transDate($a)) <=> ($dateHash{$b} ||= transDate($b)) } @startDates; return $sortedDates[0]; }; # johngg's method. # my $rcJohnGG = sub { return ( map {join q{-}, reverse split /-/} sort map {join q{-}, reverse split /-/} @startDates )[0]; }; # Run all three on data to prove they come up with # the same answer. # print q{$rcCog->() - }, $rcCog->(), qq{\n}; print q{$rcJediWizard->() - }, $rcJediWizard->(), qq{\n}; print q{$rcJohnGG->() - }, $rcJohnGG->(), qq{\n}; # Run the benchmark # cmpthese (50, { Cog => $rcCog, JediWizard => $rcJediWizard, JohnGG => $rcJohnGG }); # JediWizard's date translation routine. # sub transDate { my $date = shift; $date =~ s/(\d{2})-(\d{2})-(\d{4})/$3$2$1/; return $date; }