reading a Windows dir into an array, sorting by date, grabbing most recent

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tevo
    New Member
    • Aug 2008
    • 2

    #1

    reading a Windows dir into an array, sorting by date, grabbing most recent

    Hello,
    I'm trying to do a Perl script on Windows (wish it was Unix) that goes to a directory, figures out which files are most recent, within the last week, then copies them to another dir. I'm stuck at the sorting of the files in a directory. This part of the code returns a list but it's not sorted by date:

    Code:
    opendir(INPUTINFO, ".") or die "Doesn't work: $!";
       my @xmlfiles = grep /\.xml$/, readdir INPUTINFO;
       my@sorted = 
    	map {join'/',(split/-/)[1,2,0]}
    	sort
    	map {join'-',(split'/')[2,0,1]}
        	qw(12/31/2000 12/26/2000 01/01/2001), @xmlfiles;
       	print "$_\n" for @xmlfiles;
       	print "\n";
    I'm guessing it's the sort. Would file::stat work better?
    Thanks,
    TEVO
    Last edited by eWish; Aug 20 '08, 11:30 PM. Reason: Please use the code tags
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    To sort the files based on modified time/date, you can make use of stat() function :
    Code:
    print "$_\n" foreach(sort {(stat($a))[9]<=>(stat($b))[9]} @xmlfiles);

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      Originally posted by nithinpes
      To sort the files based on modified time/date, you can make use of stat() function :
      Code:
      print "$_\n" foreach(sort {(stat($a))[9]<=>(stat($b))[9]} @xmlfiles);
      Yes, but that is not very efficient since it will have to stat() files more then one time. Better to build an array or hash of sort keys first, then sort the keys.

      Comment

      • nithinpes
        Recognized Expert Contributor
        • Dec 2007
        • 410

        #4
        Originally posted by KevinADC
        Yes, but that is not very efficient since it will have to stat() files more then one time. Better to build an array or hash of sort keys first, then sort the keys.
        Agreed. Thanks for the update Kevin :)

        Code:
         $stathash{$_} = (stat($_))[9] foreach(@xmlfiles);
         print "$_\n" foreach(sort {$stathash{$a}<=>$stathash{$b}} keys %stathash);

        Comment

        Working...