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

anyone got a snippet of code that deletes dirs and sub dirs only if the target is empty.

Replies are listed 'Best First'.
Re: delete dir if empty on nt
by BrowserUk (Patriarch) on Nov 18, 2002 at 12:47 UTC

    From perlfunc:rmdir...

    rmdir FILENAME rmdir Deletes the directory specified by FILENAME if that directory is empty +. If it succeeds it returns true, otherwise it returns false and sets + $! (errno). If FILENAME is omitted, uses $_

    Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
    Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
    Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
    Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

Re: delete dir if empty on nt
by Aristotle (Chancellor) on Nov 18, 2002 at 12:28 UTC
    What target? Exactly what are your conditions? Your question could be a little clearer.

    Makeshifts last the longest.

      appologies for the lack of clarity. I am working on tidying up disk space based on age of files using the -M switch. If the file is over -M days the file is deleted. The program I have which works sucesfully traverses a tree and deletes the files that meet the test condition. Naturaly this then leaves me with a set of dirs which may or may not be empty. Therefore the net thing to do is find and delete any empty directories. At this stage I dont care about their age. Hope this is clearer
        I assume you're doing the right thing and using File::Find to find the files in question - then the job can be done at the drop of a hat. The postprocess predicate to find() calls a given sub just before finally exiting a directory. That's all we need - we simply attempt to remove the directory and if there's anything in there, that will just fail harmlessly. It's less work for both us and the computer than if we tried to check manually.
        #!/usr/bin/perl -w use strict; use File::Find; my $max_age_days = 120; find({ wanted => sub { unlink if -f $_ and -M _ > $max_age_days }, postprocess => sub { rmdir $File::Find::dir }, }, @ARGV);

        Makeshifts last the longest.

(tye)Re: delete dir if empty on nt
by tye (Sage) on Nov 18, 2002 at 16:57 UTC
      thanks looks useful so will try tomorrow at place of daily grind.