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
- 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
- Flex Remove Allow Deny Option
- Tool Igqjj.exe Manual Remove
- Remove Enlfxgw Online Tool Manual Removal
- Perl Here Document
- Perl Fetching
- Perl Dbi Tutorial
- Install Perl Ubuntu
- Php Json In Perl
- Json Perl Join File

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