http://qs1969.pair.com?node_id=437881

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

Hello Monks.
The situation is:
I used File::Find to delete files .Now I have many empty directories.
Can I take the deepness of current directory as variable-
thus I'll be able to run "rmdir" not more than this
deepness. Thanks in advance.!

Replies are listed 'Best First'.
Re: Need to delete empty directories.
by rinceWind (Monsignor) on Mar 09, 2005 at 12:57 UTC
    The point is, that you have an empty skeleton directory tree. The toppermost directories are not themselves empty as they contain directories.

    Here is a technique I use in one of my module tests for removing the directory 'test' and anything below:

    find( { bydepth => 1, wanted => sub { if (-d $_) { rmdir $_; } else { 1 while unlink $_; } }, }, 'test') if -d 'test'; rmdir 'test';
    In case you are wondering about 1 while unlink, check out the node.

    --
    I'm Not Just Another Perl Hacker

Re: Need to delete empty directories.
by sh1tn (Priest) on Mar 09, 2005 at 12:49 UTC
    use File::Find; my @dirs; my @search_dirs = qw(. ..); find(\&wanted, @search_dirs); sub wanted { -d && push @dirs, $File::Find::name } # do sm.th. with directories in @dirs


      I can delete empty directory with rmdir.
      Since if I delete some directory -it's parent directory can
      become empty-I need to delete it too.
      Thus what I need is loop of deletions of empty directories.
      However I want to limit this loop to the maximum
      deepness.
      Thanks in advance.
        use strict; use File::Find; my @topdirs = @ARGV; my @rmdirs; find( sub { -d and push @rmdirs, $File::Find::name }, @topdirs ); rmdir for reverse @rmdirs;


Re: Need to delete empty directories.
by merlyn (Sage) on Mar 09, 2005 at 14:56 UTC
Re: Need to delete empty directories.
by dmorelli (Scribe) on Mar 09, 2005 at 14:39 UTC
    Here's a way that 'schedules' a dir for removal later only when a file was removed within it.

    #! /usr/bin/perl -w use strict; use File::Find; my @dirs; # Process each file that was found sub wanted { # Use your criteria here for what to delete if (/foo/) { # Delete the file unlink $_; # Save the dir for later push @dirs, $File::Find::dir; } } # Replace . with your starting dir find \&wanted, '.'; # Now try to remove the dirs, rmdir will fail if the dir isn't empty rmdir $_ foreach reverse @dirs;

    Update: oops, just read above node about removing dirs with other dirs inside them. Modified the script to not use the hash for dir path storage, but instead use the reverse list.