glob a directory then sort by timestamp

J

jhellma1

All,

I am trying to glob a directory, storing the filenames into an array.
The trick is that I then want to sort that array by the files'
timestamps. Is there an easy way to do this?

TIA!
 
J

Jürgen Exner

I am trying to glob a directory, storing the filenames into an array.
The trick is that I then want to sort that array by the files'
timestamps. Is there an easy way to do this?

Looping through and stat()ing hundreds or thousands of files individually is
going to be slow. Depending upon _which_ timestamp (created, accessed,
modified, ...) you want to sort by it may be significantly faster to call an
external program (e.g. ls) with the proper parameters and simply capture the
output.

jue
 
T

Tony Curtis

All,

I am trying to glob a directory, storing the filenames into an array.
The trick is that I then want to sort that array by the files'
timestamps. Is there an easy way to do this?

The glob() is going to do its own sort, so that would be wasteful.

Better to opendir(), grep() a readdir() for the required items, closedir()
and then sort those by stat()ing for {modified,changed,accessed} time.

Don't forget to see "perldoc -f stat" about the use of "_" to minimize
file system hits.

hth
t
 
J

John W. Krahn

All,

I am trying to glob a directory, storing the filenames into an array.
The trick is that I then want to sort that array by the files'
timestamps. Is there an easy way to do this?

TIA!

For example (UNTESTED):

my $dir = 'something';

opendir my $DH, $dir or die "Cannot opendir '$dir' $!";

my @sorted_files =
map $_->[1],
sort { $a->[0] <=> $b->[0] }
map -f "$dir/$_" ? [ ( stat _ )[9], $_ ] : (),
readdir $DH;



John
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top