in reply to Sorting according to date

Use Date::Calc, here is an example:
#! /usr/bin/perl -w use CGI qw/:standard/; # first install module Date::Calc use Date::Calc qw(Date_to_Days Add_Delta_Days check_date); #@array=readpipe 'ls 'directory'/'subdirectory'.*html' ; @array=readpipe 'ls ./tmp/*html' ; # we will be sorting later #sort @array; @headings=('Title','Issue Date'); @rows=th(\@headings); foreach $n (@array) { open (HTMLFILE,$n); $issue_date=""; while (<HTMLFILE>) { if (m/<TITLE>(.+)<\/TITLE>/i){$title=$1}; # had to change / in the middle? if (m/<o:Description>(.+)<o:Description>/i) {$issue_date=$1}; } close HTMLFILE; #push(@rows, td([$title,$issue_date]) push(@temp_rows,[$title, $issue_date, # in case your date looks like "DD.MM.YYYY" Date_to_Days((split(/\./, $issue_date, 3))[2,1,0]) ]); } for my $i (sort {$a->[2] <=> $b->[2] } @temp_rows) { push(@rows, td([@{$i}[0,1]])); } print table({width=>"100%",border=>"1",bordercolor=>"#d9dae6",cellspacing=>" +1",cellpadding=>"1"},Tr({bgcolor=>"#97a5f0"},\@rows));

Replies are listed 'Best First'.
Re: Re: Sorting according to date
by sauoq (Abbot) on Jun 09, 2003 at 21:19 UTC

    First you assume the date format he is using and then you go on to suggest a byzantine method of sorting dates in that format...

    If his dates really are in a format like "DD.MM.YYYY" then Date::Calc is hardly necessary:

    my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, join "", reverse (split /\./) ] } @dates;

    -sauoq
    "My two cents aren't worth a dime.";
    
      I like your solution, it is elegant but a bit slower. Conversion of date strings to integers is expensive, but it pays off in the sorting faze. Dates that are close together have 4 to 6 equal characters from the beginning of the string, and the for loop is also faster than map. I made a couple of benchmarks to verify that. The difference in speed is not significant.
      I had to assume some date format to be able to produce working solution. It is easy to modify for different format.
        Thank you, O enlightened ones.

        Regards

        Campbell