Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How do I delete a directory without emptying it first?

by trala (Initiate)
on Jan 17, 2002 at 05:07 UTC ( [id://139413]=note: print w/replies, xml ) Need Help??


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^

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://139413]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-16 04:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found