37fa9baa82d848871535d6e2101221e5

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.

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 !

0706636fd5e30fa66019d7ffacdb5b11

Marco Valtas

October 14, 2008, October 14, 2008 22:35, permalink

1 rating. Login to rate!

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
    );
}
5d8037d6ab2ec9082a049771c588c558

Joe McMahon

November 16, 2009, November 16, 2009 02:11, permalink

No rating. Login to rate!

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 });
}

Your refactoring





Format Copy from initial code

or Cancel