Friday, October 26, 2007

Using Perl To Figure Out How Old Your Files Really Are!

Here's a little something I cooked up out of job-ennui ;) It's a complicated looking, but pretty basic, script to let you know how old your files are at the instant you run it.

The outer part of the script is left out - basically just processing file names, which you can do however you wish, and dumping them into an array (@files).

This is a pretty good example of what you can do with Perl's included "stat" function ( you can do a whole lot more, as evidenced in line 5 of this script on the left hand side of the assignment).

This script would actually look a whole lot nicer if we also used Perl's built in "localtime" function (would save us all the hassle of doing division), but what fun would that be?

This is safe to try at work, unless you're supposed to be doing something else and your boss is a micro-manager ;)

Creative Commons License

This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

$now = time;
foreach $file (@files) {
$fileage_s = $now - $mtime;
print "$file :";
if ( $fileage_s < 60 ) {
printf (" %02d second(s) old", $fileage_s);
} elsif ( $fileage_s < 3600 ) {
$fileage_m = sprintf("%d", $fileage_s/60);
$fileage_s = $fileage_s-($fileage_m*60);
printf (" %02d minute(s) %02d second(s) old", $fileage_m, $fileage_s);
} elsif ( $fileage_s < 86400 ) {
$fileage_h = sprintf("%d", $fileage_s/3600);
$fileage_m = sprintf("%d", ($fileage_s-($fileage_h*3600))/60);
$fileage_s = $fileage_s-(($fileage_m*60)+($fileage_h*3600));
printf (" %02d hour(s) %02d minute(s) %02d second(s) old", $fileage_h, $fileage_m, $fileage_s);
} elsif ( $fileage_s >= 86400 ) {
$fileage_d = sprintf("%d", $fileage_s/86400);
$fileage_h = sprintf("%d", ($fileage_s-($fileage_d*86400))/3600);
$fileage_m = sprintf("%d", ($fileage_s-(($fileage_d*86400)+($fileage_h*3600)))/60);
$fileage_s = $fileage_s-(($fileage_m*60)+($fileage_h*3600)+($fileage_d*86400));
printf (" %d day(s) %02d hour(s) %02d minute(s) %02d second(s) old", $fileage_d, $fileage_h, $fileage_m, $fileage_s);
print "\n";

Until tomorrow,

, Mike