Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

The title sums up my question. I tried rmdir($old_dir) or die "Error $!"; and it says it cannot delete the directory because there are files in it.

Is there a way to give the script super permissions to delete a folder? I'm deleting a temporary folder my script makes after each run. If not, how do I delete all the files in this folder?

Replies are listed 'Best First'.
Re: How to delete non-empty directory
by Joost (Canon) on May 17, 2007 at 20:06 UTC
Re: How to delete non-empty directory
by clinton (Priest) on May 17, 2007 at 20:07 UTC
    Have a look at File::Path. It has a rmtree() function.

    It works, the only downside is that if you want to catch any errors, you need to trap $SIG{__WARN__} - annoying, to say the least.

Re: How to delete non-empty directory
by Khen1950fx (Canon) on May 18, 2007 at 21:25 UTC
    I've been using a script that a monk posted here sometime ago. It's an elaboration of swampyankee's idea:

    my $old_dir = '/path/to/old_dir'; my $result = system("rm -rf $old_dir"); print "Result: $result\n";

    It will delete directories with or without files.

Re: How to delete non-empty directory
by swampyankee (Parson) on May 18, 2007 at 15:33 UTC

    If you're really, really sure of the name of your temporary folder, you could use the system1 command:

    `rm -fr $temporary_folder`;

    I would be more than slightly paranoid about this, making sure that $temporary_folder didn't have a value such as '~' or '/' or anything that would confuse the shell.


    Notes

    1 using "system" to include backticks, qx//, etc.

    emc

    Insisting on perfect safety is for people who don't have the balls to live in the real world.

    —Mary Shafer, NASA Dryden Flight Research Center