Link to home
Create AccountLog in
Avatar of new_perl_user
new_perl_user

asked on

Delete Dircetories with contents in it

Hi,
 How to delete directories and sub directories when there are files in them in Perl
Avatar of lokiaustin
lokiaustin

The easiest way is to use backticks and just call the shell command that would do the same thing.

`rm -rf $dir`

as always there's a ton of other ways to do it, but this I think is it the most simple
See
perldoc -q "How do I delete a directory tree"

Open in new window

:

Found in /usr/share/perl/5.10/pod/perlfaq5.pod
How do I delete a directory tree?
(contributed by brian d foy)

If you have an empty directory, you can use Perl's built-in "rmdir". If the directory is not empty (so, no files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you.

The "File::Path" module, which comes with Perl, has a "rmtree" which can take care of all of the hard work for you:
               use File::Path qw(rmtree);
               rmtree( \@directories, 0, 0 );

Open in new window


The first argument to "rmtree" is either a string representing a directory path or an array reference. The second argument controls progress messages, and the third argument controls the handling of files you don't have permissions to delete. See the "File::Path" module for the details.
ASKER CERTIFIED SOLUTION
Avatar of ropenner
ropenner
Flag of Canada image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
rduke15's way would be better,  I've seen the havoc rm -r has caused in unix/linux systems, not pretty.  At least you have specific control using the module.

Jody
And system("rm -rf ...") is Unix only. Perl's rmtree works on any system on which Perl does.

The original poster didn't specify it, but if it has to run on Windows, "rm -rf" will do no harm, but no good either.