• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 146
  • Last Modified:

Delete Directory & Everything in it

Hi...
I know that unlink is the command to delete one file.
How can I remove a directory and everything in it?
0
jknickelbein
Asked:
jknickelbein
1 Solution
 
prakashk021799Commented:
If there are no subdirectories in $dir:

unlink <$dir/*>;
# remove files starting with a '.', but skip . and ..
unlink grep {m/^\.+$/ ? undef : $_} <$dir/.*>;
rmdir $dir;

If there _are_ subdirectories in $dir, you can do this recursively:

sub remove_directory($)
{
    my $dir = shift;
    chdir $dir;
    for (glob("*"), glob(".*")) {
        next if /^\.+$/;    # skip . and ..
        if (-d $_) {
            remove_subdirectory($_);
        } else {
            unlink $_;
        }
    }

    chdir '..';
    rmdir $dir;
}

You will need to add error checking to the above code.
0
 
prakashk021799Commented:
Oops! one change.

Change the call to 'remove_subdirectory' to 'remove_directory' in the above code (somewhere in the middle of the subroutine).
0
 
thoellriCommented:
# or

use File::Path;
rmtree("/the/directory/to/delete");

# tobias
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
prakashk021799Commented:
Yes. Using File::Path is definitely better. I completely forgot about it.
0
 
shlomoyCommented:
why not just use "rm -R dirname" at the prompt?
0
 
prakashk021799Commented:
> why not just use "rm -R dirname" at the prompt?

Because its not perl.
0
 
jknickelbeinAuthor Commented:
Please answer, thoellri, you're answer seems the most sensible, and it works!
Thanks!
0
 
thoellriCommented:

      use File::Path;
      rmtree("/the/directory/to/delete");

      # tobias
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now