grahm has asked for the wisdom of the Perl Monks concerning the following question:

The code below was posted to delete by "dvergin" to show an example of how to delete files after 7 days:
#!/usr/bin/perl -w use strict; my $file; my $dir_spec = '/home/archive/logs/old'; opendir(LOGDIR, $dir_spec) or die "Can't open $dir_spec: $!\n"; while ( defined($file = readdir(LOGDIR)) ) { if (-M "$dir_spec/$file" > 7) { unlink("$dir_spec/$file") or die "Can't delete $dir_spec/$file: $!\n"; } } closedir(LOGDIR);
"The key to this is the file test operator -M which returns the number of days old the given file is. Just the thing you needed."

I posted a question to this yesterday but noticed the date of the original post was back in Feb. so I'll try again..

I'm curious as to how the -M operator works. Since Unix doesn't keep track of file creation dates, does -M check for the last modified? So in the example above would the given file be deleted if it wasn't modified in the last 7 days? I'm also assuming that one could use the -M to test directories as well. Is this true? :]

Replies are listed 'Best First'.
Re: Question about - M
by mikeirw (Pilgrim) on Jun 30, 2002 at 00:54 UTC
    Yes, -M checks the age of the file (in days) since modification, so yes, the script would delete the file if it hadn't been modified within the past seven days since the script started. It should work on directories as well.
Re: Question about - M
by Zaxo (Archbishop) on Jun 30, 2002 at 05:28 UTC
    Since Unix doesn't keep track of file creation dates, ...

    Unix regards ctime in terms of the last inode modification. That may not be what you want. There are -M, -A, and -C relating to file dates. -A is not too touchable, but the other two are pretty flexible.

    See p. 100 of Camel3.

    After Compline,
    Zaxo

      -A is not too touchable, but the other two are pretty flexible.
      I'm not sure if you mean which two of the three are arbitrarily settable, but if you do, you're wrong. It's -C that is always set to "now" whenever you do anything interesting to the file, but -A and -M can be set to arbitrary values using utime.

      -- Randal L. Schwartz, Perl hacker

Re: Question about - M
by Beatnik (Parson) on Jun 30, 2002 at 10:17 UTC
    Note that -M returns the age (in days) of the file since the program started so if you plan on using an infinitly looping script, you might want to set $^T to time... $^T = time; to make sure -M returns the true age of the file. $^T contains the date/time when the script was started ad -M uses it to find the age in days.If your script has been running 10 days, and the file itself has been edited last 5 days before you started the script, normally -M would return 5.xxxxxx (minutes, seconds, etc) and not 15.xxxxxx. With that $^T, it would be 15.xxxxx
    Update: Oki, this can look confusing... rephrased a bit

    Greetz
    Beatnik
    ...Perl is like sex: if you're doing it wrong, there's no fun to it.