By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,712 Members | 1,958 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,712 IT Pros & Developers. It's quick & easy.

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

P: 2
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:

Expand|Select|Wrap|Line Numbers
  1. opendir(INPUTINFO, ".") or die "Doesn't work: $!";
  2.    my @xmlfiles = grep /\.xml$/, readdir INPUTINFO;
  3.    my@sorted = 
  4.     map {join'/',(split/-/)[1,2,0]}
  5.     sort
  6.     map {join'-',(split'/')[2,0,1]}
  7.         qw(12/31/2000 12/26/2000 01/01/2001), @xmlfiles;
  8.        print "$_\n" for @xmlfiles;
  9.        print "\n";
I'm guessing it's the sort. Would file::stat work better?
Thanks,
TEVO
Aug 20 '08 #1
Share this Question
Share on Google+
3 Replies


nithinpes
Expert 100+
P: 410
To sort the files based on modified time/date, you can make use of stat() function :
Expand|Select|Wrap|Line Numbers
  1. print "$_\n" foreach(sort {(stat($a))[9]<=>(stat($b))[9]} @xmlfiles);
  2.  
Aug 21 '08 #2

KevinADC
Expert 2.5K+
P: 4,059
To sort the files based on modified time/date, you can make use of stat() function :
Expand|Select|Wrap|Line Numbers
  1. print "$_\n" foreach(sort {(stat($a))[9]<=>(stat($b))[9]} @xmlfiles);
  2.  
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.
Aug 21 '08 #3

nithinpes
Expert 100+
P: 410
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 :)

Expand|Select|Wrap|Line Numbers
  1.  $stathash{$_} = (stat($_))[9] foreach(@xmlfiles);
  2.  print "$_\n" foreach(sort {$stathash{$a}<=>$stathash{$b}} keys %stathash);
  3.  
Aug 21 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.