I have created a perl script which will recursively delete files based on 2 command line arguments. I am attemping to add the ability for this script to clean out empty directories on it's way through also. I have tried using the rmdir command in a couple of variation, but have not been able to get this to work properly. Could someone offer any suggestion on how to correct this script? I would appreciate any ideas.
Code:
#!/usr/bin/perl -w
#######################
# Script to test functionality
# before an actual purge is run
# on a given directory.
# Live version is named without the
# word test.
#################################
use File::Find;
my $byteCount=0;
my $fileCount = 0;
my $dateCreated;
my $readable_mtime;
my $searchDir = $ARGV[0]; #read in the passed directory to test existence
my $days_of_purge = $ARGV[1]; # read in the number of days before purging.x
# Convert the days of purge to the correct Unix time.
my $converted_purge_time = $days_of_purge * 86400; # 86400 = number of seconds in 24 hours
if ( -d $searchDir) {
# Issue the find command passing two arguments
# The first argument is the subroutine that will be called for each file in the path.
# The second argument is the directory to start your search in.
finddepth(\&cleanup, $ARGV[0]);
print "$fileCount files are using $byteCount gigabytes\n";
# Subroutine that determines whether we matched the file extensions.
sub cleanup {
my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $therest) = stat($_) or die "Unable to stat $_\n";
my @t = localtime $mtime;
$date = sprintf "%02u/%02u/%02u %02u:%02u:%02u", $t[4] + 1, $t[3], $t[5] % 100, $t[2], $t[1], $t[0];
if ((time - $converted_purge_time) > $mtime) {
if ( -f ) {
print "$File::Find::name $date $size\n ";
$byteCount += $size/1024/1024/1024;
$dateCreated= $mtime;
$fileCount++;
unlink("$File::Find::name") or die "Unable to delete $File::Find::name \n";
print $File::Find::dir . "\n";
rmdir $_;
}
}
}
} else {
print "Directory does not exist\n";
}