Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
is there any way readdir to return me files by modification time ? I do  
not want keep their dates on an array and sort it . I wantone pass like  
ls -ltr

Re: readdir

Quoted text here. Click to load it


How do you think ls solves this problem? I'll give you a hint: it stat()s
all the files and creates an array...

bets there is no guarantee that the filesystem even supports modification times

Re: readdir

On Tuesday, October 29, 2013 4:06:59 PM UTC-6, George Mpouras wrote:
Quoted text here. Click to load it

Dear George,

   The readdir() function returns files in whatever order it wants.  Well,  
there's more to it than that, but you need to remember that you can't assum
e it will ever be in any meaningful order.  That's why Perl gives us the so
rt() function.

   You probably already know that if you want to sort filenames ASCII-betic
ally, you can do so this way:

   @fileNames = sort @fileNames;

   Sorting by modification time is a bit more involved.  Fortunately, you c
an use a Schwartzian Transform like this one:

   @fileNames = map
                sort {$b->[1] <=> $a->[1]}
                map {[$_, -M $_]} @fileNames;

(It is important to remember that the entries in @fileNames must contain a  
proper path to each file.  If the entries are just basenames (that is, they
 have no path) and the files are not in the current working directory, then
 this sort won't work properly.)

It's just one line long (though I had to break it up to avoid line-wrapping
).  If it's not clear to you what it's doing, I suggest you read up on Schw
artzian Transforms.  If you want to stick to the perldocs, you can read abo
ut them in perlfaq4 with the command:

   perldoc -q "sort an array"

   Schwartzian Transforms can be very helpful, especially if you want to so
rt an array of filenames in just one pass.  But they're not immediately int
uitive, which is why it would be wise to study them enough to understand ho
w to implement them in any programming language.

   I hope this helps, George.

   -- Jean-Luc

Site Timeline