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
Comments (3)
  • These two lines are stupid:

    These two lines are stupid:
    @files = map { $_ = "$dirtodel$sep$_"} @files;
    @files = map { (-d $_)?deldir($_):unlink($_) } @files;

    @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;
    $_ = "$dirtodel$sep$_" foreach @files;

    @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;

    By bob on 11 Mar, 2011
  • 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).

    By daithi on 27 Nov, 2009
    • Thanks

      That was informative :) Just did this code to provide illustration.
      By digitalpbk on 27 Nov, 2009
You may also like
On Facebook
Email Newsletter