O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing a Directory and Its Contents

Problem

You want to remove a directory tree recursively without using rm -r.

Solution

Use the finddepth function from File::Find, shown in Example 9.3.

Example 9-3. rmtree1

#!/usr/bin/perl
# rmtree1 - remove whole directory trees like rm -r
use File::Find qw(finddepth);
die "usage: $0 dir ..\n" unless @ARGV;
*name = *File::Find::name;
finddepth \&zap, @ARGV;
sub zap {
    if (!-l && -d _) {
        print "rmdir $name\n";
        rmdir($name)  or warn "couldn't rmdir $name: $!";
    } else {
        print "unlink $name";
        unlink($name) or warn "couldn't unlink $name: $!";
    }
}

Or use rmtree from File::Path, as shown in Example 9.4.

Example 9-4. rmtree2

#!/usr/bin/perl
# rmtree2 - remove whole directory trees like rm -r
use File::Path;
die "usage: $0 dir ..\n" unless @ARGV;
foreach $dir (@ARGV) {
    rmtree($dir);
}

Warning

These programs remove an entire directory tree. Use with extreme caution!

Discussion

The File::Find module exports both a find function, which traverses a tree in the (essentially random) order the files occur in the directory, as well as a finddepth function, which is guaranteed to visit all the files underneath a directory before visiting the directory itself. This is exactly what we need to remove a directory and its contents.

We have to use two different functions, rmdir and unlink. The unlink function deletes only files, and rmdir only deletes empty directories. We need to use finddepth to make sure that we’ve first removed the directory’s contents before we ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required