Perl script to remove a directory and contents recursively
This is the script for sandeep when he asked me how to delete a directory in perl. rmdir function only removes empty directories. So we need to remove the contents of the directory before removing the directory. So if the directory contains more directories / folders we would have to recursively delete all the directories under the directory. Well so here is the code just to do that.
#!/usr/bin/perl
deldir("test"); # or deldir($ARGV[0]) to make it commandline
sub deldir {
my $dirtodel = pop;
my $sep = '/';
opendir(DIR, $dirtodel);
my @files = readdir(DIR);
closedir(DIR);
@files = grep { !/^\.{1,2}/ } @files;
@files = map { $_ = "$dirtodel$sep$_"} @files;
@files = map { (-d $_)?deldir($_):unlink($_) } @files;
rmdir($dirtodel);
}
The deldir sub routine recursively iterates and deletes all the files and directories.
26 Nov, 2009
Related Searches
perl script which fetches output from search api
perl hash remove node
perl how to remove an element from an array
working sms script
script brontok remover
how to remove disabled by administrator
tool igqjj.exe manual remove
flex remove allow deny option
remove enlfxgw online tool manual removal
perl here document
perl script which fetches output from search api
perl hash remove node
perl how to remove an element from an array
working sms script
script brontok remover
how to remove disabled by administrator
tool igqjj.exe manual remove
flex remove allow deny option
remove enlfxgw online tool manual removal
perl here document
These two lines are stupid:
These two lines are stupid:
@files = map { $_ = "$dirtodel$sep$_"} @files;
@files = map { (-d $_)?deldir($_):unlink($_) } @files;
First
@files = map { $_ = "$dirtodel$sep$_"} @files;
Why assign back to $_ if you are going to overwrite the @files array in the first place? Why not do either
@files = map { "$dirtodel$sep$_"} @files;
or
$_ = "$dirtodel$sep$_" foreach @files;
Second
@files = map { (-d $_)?deldir($_):unlink($_) } @files;
The stuff inside the block doesn't return anything. So the assignment back to @files is kind of stupid. Why not just do
(-d $_)?deldir($_):unlink($_) foreach @files;
File::Path?
The standard File::Path module has a 'rmtree' function that performs the same task without the need to specify a directory separator (indeed Perl supports forward-slash as a directory separator even on Windows).
Thanks
That was informative :) Just did this code to provide illustration.