Reputation: 2491
I am trying to remove the files older than x days and got to this page on perlmonks Find files older than x days and delete them. Following is the code to do the same (which i understand removes files from the DIR that are older than 14 days):
#! /usr/local/bin/perl
my $path = '../some/hardcoded/dir/here';
die unless chdir $path;
die unless opendir DIR, ".";
foreach $file (grep {-f && (14 < -M)} readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
But i did not want to change the directory (chdir) hence changed the code as below but it is not printing file names
die unless opendir DIR, $path;
foreach $file (grep {-f && (14 < -M)} readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
even though this is printing the files correctly.
die unless opendir DIR, $path;
foreach $file (readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
I tried to search the answer but couldn't frame the question clearly. Please explain how to use grep and get the present directory files without changing directory(chdir).
Edit: Output of print Dumper map [$_, -f, -M], readdir DIR;
$VAR1 = [
'PRTS_5_Thu_May_8_11-47-19_2014.pdf',
undef,
undef
];
$VAR2 = [
'.',
'',
'0.0891203703703704'
];
$VAR3 = [
'PRTS_49_Thu_May_8_12-31-11_2014.pdf',
undef,
undef
];
$VAR4 = [
'PRTS_34_Thu_May_8_12-27-03_2014.pdf',
undef,
undef
];
$VAR5 = [
'..',
'',
'9.02722222222222'
];
Edit 2: When i change the $path from '../some/hardcoded/dir/here' to '.'. I am getting the files correctly.
Upvotes: 2
Views: 1977
Reputation: 5069
You could change the date of a linux file using touch (for testing). I think your problem is that readdir returns only the filename and not the full path for the file.
You could test a code this way (longer but easier to understand):
#! /usr/local/bin/perl
use strict;
use warnings;
my $dir = "/some/hardcoded/dir/here";
die unless opendir DIR, $dir;
foreach my $file (readdir DIR) {
next if $file eq '.' or $file eq '..';
$file = $dir.'/'.$file;
print "found $file, mtime: ".(-M $file)."\n";
if (-f $file && (14 < -M)){
print "unlinking $file\n";
}
}
closedir DIR;
Upvotes: 2