Perl And Sort Dir By Date

Need some help again! :wink:


opendir (DIR,"/home/dir");
     @dir=readdir(DIR);
        closedir(DIR);
         @dir = sort(@dir);

That will sort all contents of the dir by name.
Is there a way to sort the conents by when they were created?

So if file A was created on 8/14/01 and file B on 7/12/01, it should have B before A?

Any ideas?
Tx

I’m pretty sure I have a solution, I just need to consult a Perl book which covers custom sorting. I’ll give you the code ASAP.

Here is a solution:-

$DirName = "/john/simrw";

# Get a list of the files
opendir(DIR, $DirName);
@Files1 = readdir(DIR);
closedir(DIR);

# Loop thru each of these files
foreach $File (@Files1) {
	
	# Get information (including last modified date) about file
	@FileData = stat($DirName."/".$File);
	
	# Push this into a new array with date at front
	push(@Files, @FileData[9]."&&".$File);
	
}

# Sort this array
@Files = reverse(sort(@Files));

# Loop thru the files
foreach $File (@Files) {
	
	# Get the filename back from the string
	($Date,$FileName) = split(/\\&\\&/,$File);
	
	# Print the filename
	print "$FileName<BR>";
	
}

I dunno if this may be a long way around the problem but it works.

It currently sorts them with newest files at the beginning of the array - to do it the other way around change @Files = reverse(sort(@Files)); to @Files = sort(@Files);

You almost had it.
This sorts by the modification time.


$dir = "/home/dir";
opendir (DIR, $dir);
     @dir=readdir(DIR);
        closedir(DIR);
         @dir = sort { -M "$dir/$a" <=> -M "$dir/$b" } (@dir);

Hi,

Tx for all the help.
However, I didn’t want to sort by modification, I wanted to sorty by when the file was originally created.
Do you know of any method I can use?

Tx!