Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

List files in order of last modified - help

Status
Not open for further replies.
Apr 13, 2006
9
GB
Hey ok i would appreciate any help you very helpful people can give me on this. below is the piece of code i use to display a list of all files within a folder. it displays them great but i want it to display them in the order they were last modified.

opendir THEDIR, "$config{'basepath'}/gigfiles" or &error("Unable to open directory: $!");
readdir THEDIR; readdir THEDIR;
my @allfiles = readdir THEDIR;
closedir THEDIR;
my $file;
foreach $file (sort @allfiles) {
$file =~ s/.dat$//;

That code reads all the files in the directory and then i use $file inside my output which displays them on the screen. What changes do i make to that code to display them in order of last modified please??

thank you in advance for any help you can offer. xx
 
You first have to get the modified time for every file and store it with the file name. Something like this

Code:
$dir = qq~$config{'basepath'}/gigfiles~;
opendir THEDIR, "$dir" or &error("Unable to open directory: $!");
my @allfiles = readdir THEDIR;
closedir THEDIR;
my $file;
foreach $file (@allfiles) {
        next if $file=~ /^\.*$/;  #so you can take out the dot directories
	($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file);	
	$files{$file} = $mtime;
}

#then go that link and you will find something like this 
foreach $key (sort { $hash{$a} cmp $hash{$b} } keys %files) {
	print $key."\n";
}

bytheway you don't need to put readir 2000 times! (unless it was a typo, in which case sorry to mention it)


``The wise man doesn't give the right answers,
he poses the right questions.'
TIMTOWTDI
 
If you only need the $mtime value from the stat command, it's more efficient to slice the array in the assignment:

Code:
$files{$file} = stat($file)[9];

replaces all this:

Code:
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file);    
    $files{$file} = $mtime;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top