Delete files in directory using perl

Hello All
I am implementing my task in Perl and i found an issue.
What i want to do is to remove files from the directory which were made 20 days back using Perl script

Use the below code to delete multiple files in perl.

#!/usr/bin/perl

@files = ("file1.txt","file2.txt","file3.txt");
foreach $file (@files) {
    unlink($file);
}

ya thats correct but how the code will calculate that the the selected file was made 20 days back

the stat function perldoc -f stat lets you know what the inode change time for a file is so combining the two we get... left as an exercise for the reader

1 Like
perl -e 'for(<*>){((stat)[9]<(time-(20*86400)))&&unlink}'
1 Like

Thanks to all
@balajesuri: can you please explain your code i didn't get it clearly

Try the below code, and try to change the parameter 86400 * no of days to make it desire to the requirement.

my $dir = '/home';
opendir(DIR,$dir) || die "Can't open $dir : $!\n";
my @files = readdir(DIR); 
close(DIR);

foreach my $file(@files)
{
	my $now = time;
	my @stat = stat("$dir/$file");
	if ($stat[9] < ($now - 86400))
	{
		print "Deleting $dir/$file...";
		unlink("$dir/$file");
		print "Done.\n";
	}
}
1 Like

Hi Rksiva
this code will delete all the files which is formed 1 days back. But i want only that file should be deleted which is formed 1 day back.
but not the file which is formed 2 days back

@parthmittal2007:
stat("filename") --> displays file status. 9th element of stat gives the last modification time of file in seconds from epoch.
time --> gives current time in seconds from epoch

So, I'm checking if the last modification time of each file in seconds from epoch is less than current time minus 20 days in seconds from epoch. If this condition satisfies, then delete the file.

And plagiarism is bad :smiley:

@balajesuri:
this will delete all the files which were formed 20 days back but i want only those files to be deleted which were made 20 days back, not the files which were made 21 or more days back