Perl script to remove a directory and contents recursively

2009
26
Nov
2

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.

Similar Posts
Related Searches




Comments

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.

Post new comment

The content of this field is kept private and will not be shown publicly.