|
|
OverviewDelete old temporary files in multiple directories using File::Find.
Flow
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 codemy $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
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. |