- Perl ›
- File operation ›
- here
Delete directories with hierarchy at once
Use the rmtree of File::Path module to delete directories with hierarchies all at once. The return value of rmtree is the number of files that could be deleted.
use File::Path 'rmtree'; rmtree $dir;
Example
This is an example to delete directories with a hierarchy at once.
use strict;
use warnings;
use File::Path 'rmtree';
# Delete the directory
# Preparation (creating a directory)
my $dir1 = "dir_20080527_ $$";
my $dir2 = "$dir1/dir2";
mkdir $dir1
or die "Unable to create $dir1.:$!";
mkdir $dir2
or die "Unable to create $dir2.:$!";
print "Preparation: $dir1 and $dir2 have been created.\n\n";
print "1: Delete hierarchical directories at once.\n";
{
# To catch the warning, use the __WARN__ signal
# There is no choice but to use a signal handler to capture.
# (For old rmtree implementations)
# The content of the warning is stored in the first argument.
local $SIG{__ WARN__} = sub {
my $msg = shift;
die "$msg";
};
if (-d $dir1) {
# If warn is called in the rmtree function,
# Move to the above sub {} and exit with die.
rmtree($dir1);
print "$dir1 has been deleted.\n";
}
}
(Reference) local - Temporarily save and restore a package variable
Perl ABC