use File::Spec;
sub purge_archive{
print "\nPurging files from: $_[0]\n";
opendir(DIR,$_[0]) or die "Cannot open $_[0]: $!";
my @files = grep{!/^\./ } readdir(DIR);
foreach my $file (@files){
unlink File::Spec->catfile($_[0],$file) or die "Can't remove files from $_[0]: $!";
}
closedir(DIR);
}
Refactorings
No refactoring yet !
Marco Valtas
October 14, 2008, October 14, 2008 22:35, permalink
Hi, usually I use File::Find for a recusive removal of files, it´s simple and fast (example bellow). For the problem you stated I quote the perldoc of readdir function:
"If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir there, it would have been testing the wrong file."
So if you check the doc there´s a example similar to yours, using File::Spec is not dirty, is portable! But you can, as the perldoc mention, just chdir to remove the files.
Hope this helps.
#!perl
sub purge_archive {
my $dir = shift;
die("$dir is not a directory!\n") unless -d $dir;
opendir(DIR, $dir) || die "Can't opendir $dir: $!";
chdir($dir) or die "Can´t change to dir $dir: $!";
@files = grep { !/^\./ && -f } readdir(DIR);
unlink @files;
closedir DIR;
}
sub purge_archive_recursive {
my $dir = shift;
die("$dir is not a directory!\n") unless -d $dir;
find(
sub {
unlink unless /^\./ or -d;
},
$dir
);
}
Joe McMahon
November 16, 2009, November 16, 2009 02:11, permalink
As suggested by 'perldoc -f rmdir'.
use File::Path qw(remove_tree);
sub purge_archive{
my $dir = shift;
print "\nPurging files from: $dir\n";
remove_tree($dir, {keep_root => 1 });
}
I want to remove all files from a given directory. This code returns the list of files except for '.' files that I loop over and remove each one separately. The reference states that unlink accepts a LIST (arrays or even wildcards), but when I pass the file array from readdir it states it can't find the files. I added the reference to File::Spec to provide a complete path, but it feels very dirty to me.