readdir

G

George Mpouras

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
 
J

jl_post

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 want one pass like

ls -ltr


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 assume it will ever be in any meaningful order. That's why Perl gives us the sort() function.

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

@fileNames = sort @fileNames;

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

@fileNames = map {$_->[0]}
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, theyhave no path) and the files are not in the current working directory, thenthis 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 Schwartzian Transforms. If you want to stick to the perldocs, you can read about them in perlfaq4 with the command:

perldoc -q "sort an array"

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

I hope this helps, George.

-- Jean-Luc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top