in reply to How do I delete a directory without emptying it first?

Okay, just came up with this for a script I am working on. If this is really stupid, please someone let me know!
use File::Find; finddepth (\&remove_dir, "$directory"); rmdir ( "$directory" ) or die ("Could not remove $directory"); sub remove_dir { # for a directory, this will be 0 if ( ! (stat("$File::Find::name"))[7] ) { rmdir("$File::Find::name"); } else { unlink("$File::Find::name"); } }
In theory, finddepth will find the deepest items first (files inside the directories). Once the files are unlinked, the directories will be empty and can be removed.

Replies are listed 'Best First'.
Re: Answer: How do I delete a directory without emptying it first?
by gav^ (Curate) on Jan 17, 2002 at 07:11 UTC
    To make your example a bit shorter you could go for:
    use File::Find; finddepth( sub { (-d) ? rmdir : unlink }, $directory);

    But I would recommend using File::Remove as per my example.

    gav^