natol44 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

Where did I make an error? Files are not sorted ?!

I have an array of files in @filelist and want to put the files, sorted by last modification date, in a new array @sorted


foreach $file (sort by_last_mod @filelist) {push (@sorted,$file);}

sub by_last_mod {
my $adate = (stat($a))[9];
my $bdate = (stat($b))[9];
return $adate <=> $bdate;
}


Result: @sorted is the exact copy of @filelist. Where is my error?

Thanks!

Replies are listed 'Best First'.
Re: Sorted by date file not working?!
by CountZero (Bishop) on Mar 04, 2010 at 07:30 UTC
    This works:
    use strict; use warnings; use 5.010; my @filelist = glob('c:\data\perl\bin\*.bat'); {local $,="\n"; say 'Unsorted', @filelist;} say; my @sorted = sort by_last_mod @filelist; {local $,="\n"; say 'Sorted', @sorted}; sub by_last_mod { my $adate = ( stat($a) )[9]; my $bdate = ( stat($b) )[9]; return $adate <=> $bdate; }
    Output:
    Unsorted c:\data\perl\bin\ap-iis-config.bat c:\data\perl\bin\ap-update-html.bat c:\data\perl\bin\ap-user-guide.bat c:\data\perl\bin\c2ph.bat (...) Sorted c:\data\perl\bin\latexmk.bat c:\data\perl\bin\dprofpp.bat c:\data\perl\bin\exetype.bat c:\data\perl\bin\perlglob.bat (...)
    Maybe your initial array was already sorted?

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Sorted by date file not working?!
by jwkrahn (Abbot) on Mar 04, 2010 at 07:15 UTC

    How do you populate the @filelist array?    Are you using readdir?

    foreach $file (sort by_last_mod @filelist) {push (@sorted,$file);} could more simply be written as: push @sorted, sort by_last_mod @filelist;.

      Yes I am using readdir.

      I checked that @filelist is correct (really contains the file names), and that it is not already sorted (LOL);

      After the sort, I check @sorted and see that it is exactly the same then @filelist. No sort at all was done.

      I also used File::Stat, same result :(

        If you are using readdir then you have to prepend the directory name to the file name when you do the stat, for example:

        opendir DH, $dir or die "Cannot opendir '$dir' $!"; my @filelist = readdir DH; my @sorted = sort by_last_mod @filelist; sub by_last_mod { my $adate = ( stat "$dir/$a" )[ 9 ]; my $bdate = ( stat "$dir/$b" )[ 9 ]; return $adate <=> $bdate; }