Wells-it.com - Web Hosting

delete file older than x days

You are viewing this site as a guest. Join our community to get your questions answered and share knowledge. Active members may advertise and ask for a website critique.
merlin's picture

They have: 410 posts

Joined: Oct 1999

i'm getting into it, slowly... but, another question:
i'd like to delete all files in a directory, which are older than, let's say, 20 days.
that's what i have:

foreach $file (@postcarddata) {
if (-M $file > 20) {
print "$file<br>";
unlink $file;
}
}

'

another thing i tried:

foreach $file (@postcarddata) {
next unless -M $file > 12;
unlink $file;
}

'

but well, it's not really working... what am i doing wrong? thanx for your help!

They have: 161 posts

Joined: Dec 1999

You should be testing the return value of unlink() -- maybe then, you'll have a better idea of why it's not working. It works for me:

opendir DIR, $path or die "can't read $path: $!";
while (defined(my $file = readdir DIR)) {
  # use the path to the file, not just the name of the file
  next unless -f "$path/$file";
  if (-M "$path/$file" >= 7) {
    # delete if a week old
    unlink "$path/$file" or warn "can't delete $path/$file: $!";
  }
}
closedir DIR;

'

Jeff japhy Pinyan -- accomplished Perl teacher, author, and hacker

Are you a Monk?
Perl Guru Forums
Visit #perl on DALnet

merlin's picture

They have: 410 posts

Joined: Oct 1999

that worked! i didn't give the path of the file, that's what i made wrong, probably...
anyway, now it's working and it's great! thanks japhy!

They have: 117 posts

Joined: Mar 2000

Just wondering, how would you delete all files that haven't been modified within x number of days?

--Edge

They have: 161 posts

Joined: Dec 1999

Well, now I feel kinda silly. The code I'd posted was for files that have not been updated in X days. So that answers your question, Edge.

You can't get at the creation time of files, alibababa, so the code you're using is testing for when the file was last modified. That might be what you wanted, though.

Jeff japhy Pinyan -- accomplished Perl teacher, author, and hacker

Are you a Monk?
Perl Guru Forums
Visit #perl on DALnet

merlin's picture

They have: 410 posts

Joined: Oct 1999

thanks japhy, you told me what i was looking for. and beside, the hard thing (at least for me) is the syntax. for changing the file-selection i only have to change the letter (-A, -C, -M).