|
|
OverviewListing files in updated order. For simple listing, refer to Listing files in a directory(folder). For sorting alphabetical order, refer to Sorting files.
Flow
A sample code
my $dir = "filedir";
opendir(DIR, "$dir") or die "Cannot open $dir.";
my @filelist = grep !/^\./, readdir DIR;
closedir(DIR);
my %timefile;
foreach my $file (@filelist){
my $mtime = (stat("$dir/$file"))[9];
push @{$timefile{$mtime}},"$file";
}
print "<ul>\n";
foreach my $time (sort {$b <=> $a} keys %timefile){
foreach (@{$timefile{$time}}){
print "<li>$_</li>\n";
}
}
print "</ul>\n";
Description of the codemy $dir = "filedir"; opendir(DIR, "$dir") or die "Cannot open $dir."; my @filelist = grep !/^\./, readdir DIR; closedir(DIR); $dir contains the directory name you want to display the contents of. Open the directory by opendir. If failed, terminate script with a error message. Read out the contents of the file handle DIR using readdir. The read data is pruned by grep and extract the necessary files and put them into the array @filelist. In this example, the all files except the files starting from dot. Then close the file handle DIR.
my %timefile;
foreach my $file (@filelist){
my $mtime = (stat("$dir/$file"))[9];
push @{$timefile{$mtime}},"$file";
}
$file is the name of the file from which you want to obtain the time information. By using state function, attributes are returned as an array. The tenth element(element number nine) of the array contains the update time and put it into $mttime. The other values are discarded. The value is epoch and 0 means January 1st, 1970, 0:0:0. The other return value of the stat functoin is
my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,
$mtime,$ctime,$blksize,$blocks)=stat("$file");
The access time is $atime, inode update time is $ctime. $size indicates file size. Then, make a hash which contains update time and file name as a pair. This allows to obtain file name from update time. In this example,
push @{$timefile{$mtime}},"$file";
allows to have multiple files which updated in the exactly same time. If the file name is specified as follows,
$timefile{$mtime} = "$file";
it overrides the file name previously written. In order to avoid this case, use the reference of the hash and keep multiple files corresponding to an updated time.
print "<ul>\n";
foreach my $time (sort {$b <=> $a} keys %timefile){
foreach (@{$timefile{$time}}){
print "<li>$_</li>\n";
}
}
print "</ul>\n";
Display the file one by one with foreach. In this time, sort the array in update time order. By doing {$b <=> $a}, it sorts in the order of bigger epoch value, which means newer order. Since there could be multiple files in one key, open the array reference and extract each of them. |