Deleting old temporary files in multiple directories automatically using File::Find

Top Japanese page




Overview

Delete old temporary files in multiple directories using File::Find.

Flow

  1. Open a directory temporary files reside
  2. Put the files you want to delete into an array
  3. check the update time of those files
  4. If it past specified time, delete it

A sample code

 use File::Find;
 
 my $prefix = 'tmp_';
 my $expire = 60;
 my $now = time;
 
 my @tmpdir = qw(tmpdir1 tmpdir2 tmpdir3);
 
 find(\&wanted, @tmpdir);
 
 sub wanted { 
    return unless (/^$prefix.*\.tmp$/ and -e );
    my $mtime = (stat("$_"))[9];
    if ($now > $mtime + $expire * 60){
        unlink("$_");
    }
 }

Description of the code

 my $prefix = 'tmp_';

Assuming temporary files have the prefix tmp_. Just for convenience, put it into $prefix.

 my $expire = 60;

Set expiration time. Where 60 minutes is specified.

 my $now = time;

Get current time.

 my @tmpdir = qw(tmpdir1 tmpdir2 tmpdir3);

Put directories which are stored temporary files in. Multiple directories can be specified.

 find(\&wanted, @tmpdir);

Enter to the directories by find method and perform &wanted on each file. The first argument gets a reference of a function.

 sub wanted { 
    return unless (/^$prefix.*\.tmp$/ and -e );

In &wanted, the process enters in each direcoty and file name is stored in $_. IF tmp_*.tmp exists in the direcotry, proceed and if not, return to the main.

    my $mtime = (stat("$_"))[9];

Get file update time. $mtime contains updated time.

    if ($now > $mtime + $expire * 60){

If $now is $mtime + $expire * 60, it means the file past more than 60 minutes. So delete it in if block. If not, do nothing.

        unlink("$_");
    }
 }

Delete in the if block using unlink.