6.10 Finding the Age of a File
6.10 Finding the Age of a File
Perl provides with several functions to find the age of a file or directory. They look like the file test operators because each has a - sign in front. The three age functions or operators are -M, -A and -C. In Unix, a node is maintained for each file or directory that exists in the system. Among other information, the information that a node contains three pieces of time information: the time the file was last modified, the time file was last accessed, and the time the node information for the file was last changed. The node information for a file can be changed even if the file’s contents are not modified, e.g., when a file is accessed, or its ownership changed, etc. The first program in this section, simply takes a list of files as command-line arguments, and iterates over all the files passed as argument and print the three pieces of time information stored for it. Perl returns the time in number of fractional days.
Program 6.15
#!/usr/bin/perl
for ($i = 0; $i <= $#ARGV; $i++){
$filename = $ARGV[$i];
print "\n\nFile no $i: $filename\n";
printf "\tFile last modified: %4.4f days ago.\n", -M $filename;
printf "\tFile last accessed: %4.4f days ago.\n", -A $filename;
printf "\tFile information last changed: %4.4f days ago\n", -C $filename;
sleep (1);
}
After processing a file, the program waits a second before presenting information on the next file or directory. The sleep function does this. The output of the program, when called with a command-line argument * meaning all files in the current directory, looks something like what is given below for one file.
File no 35: sizeR.pl File last modified: 12.1289 days ago. File last accessed: 4.1983 days ago. File information last changed: 12.1289 days ago
Since file ages are provided in fractional days, in some circumstances it may have to be converted to minutes, seconds, etc., for presentation.
The next program takes a list of files and directories as command-line argument and prints the oldest file where age is counted in terms of modification. In other words, it prints the file that was modified the earliest.
Program 6.16
#!/usr/bin/perl
$oldest_age = 0;
while (@ARGV){
$file = shift @ARGV;
$age = -M $file;
if ($oldest_age < $age){
$oldest_name = $file;
$oldest_age = $age;
}
}
print "The oldest file is $oldest_name.\n";
print "It is $oldest_age days old.\n";
When called with a command-line argument of *, meaning all files in the current directory, the output of the program looks something like the following.
The oldest file is printfile.pl. It is 1168.4364 days old
