How can I read the files in a directory in sorted order?

BrianH picture BrianH · Jan 12, 2009 · Viewed 24.5k times · Source

When I read a directory in Perl with opendir, readdir, and closedir, the readdir function doesn't seem to read the files in any specific order (that I can tell).

I am reading a directory that has subdirectories named by epoch timestamp:

1224161460
1228324260
1229698140

I want to read in these directories in numerical order, which would put the oldest directories first.

When I use readdir, the first one it reads is 1228324260, which is the middle one. I know I could put the directory contents in an array and sort the array, but is there an option I can pass to readdir to read in sorted order? Or maybe a more elegant way of accomplishing this than pushing everything into array and sorting the array? There are probably modules out there to do this too, but it is difficult to get modules installed in our environment, so unless it is a built-in module I'd prefer to not use modules...

Thanks!

EDIT As requested, I am posting the code that I am using:

opendir( my $data_dh, $data_dir ) or die "Cannot open $data_dir\n";
while ( my $name = readdir($data_dh) ) {
    next if ( $name eq '.' or $name eq '..' );
    my $full_path = "${data_dir}/${name}";
    next unless ( -d $full_path );
    process_dir($full_path);
}
closedir($data_dh);

Answer

Andrew Barnett picture Andrew Barnett · Jan 12, 2009

readdir can be called in array context, so just do this:

opendir( my $data_dh, $data_dir) or die "Cannot open $data_dir\n";
my @files = sort { $a <=> $b } readdir($data_dh);
while ( my $name = shift @files ) {
...