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

I have the following code but it's telling me every directory is empty... Is it possible to get this to actually work to find empty directories or do I have to use open dir etc?

#!/usr/bin/perl # emptydir # Checks for empty directories # Ver 0.1 Nov 2013 use strict; use warnings; use File::Find; my $drive = 'C:/Temp/'; my @empty; my $ndirs = undef; my $dsize = undef; find(\&listing, $drive); #Do stuff here foreach my $files (@empty) { print "Found empty folder $files\n"; } print "Found $ndirs folders in total\n"; sub listing{ if (-d $File::Find::name) { my $dsize = (stat($File::Find::name))[7]; if ($dsize == 0) { push @empty, $File::Find::name; } $ndirs++; } }

Replies are listed 'Best First'.
Re: Can File:Find be used to find empty dirs?
by Kenosis (Priest) on Nov 20, 2013 at 06:21 UTC

    Consider using File::Find::Rule::DirectoryEmpty which inherits File::Find::Rule to recursively find empty directories:

    use strict; use warnings; use File::Find::Rule::DirectoryEmpty; my $dir = 'C:/Temp/'; my @emptydirs = File::Find::Rule->directoryempty->in($dir); print "$_\n" for @emptydirs;

    Hope this helps!

      Thanks for the code looks simple enough, I'll just have to convince IT to install that module. Thanks to reply above this one too.

        You're most welcome, PerlPlay!

Re: Can File:Find be used to find empty dirs?
by dasgar (Priest) on Nov 20, 2013 at 06:01 UTC

    I would recommend checking out File::Find::Rule, which includes the ability to easily check if the "file" is a directory and if it is empty.

Re: Can File:Find be used to find empty dirs?
by 2teez (Vicar) on Nov 20, 2013 at 09:03 UTC

    Hi PerlPlay,
    Of course you can still use File::Find modifying your code like so:

    use strict; use warnings; use File::Find; my $drive = $ARGV[0]; my @empty; my $ndirs = 0; find( \&listing, $drive ); #Do stuff here foreach my $files (@empty) { print "Found empty folder $files\n"; } print "Found $ndirs folders in total\n"; sub listing { return if /^\.{1,}/; if (-d) { my $number_of_files = grep $_ => glob("$_/*"); if ( $number_of_files == 0 ) { push @empty, $File::Find::name; $ndirs++; } } }
    Though it might not be as effective and as clean as what was perilously mentioned. Need I say, this was not tested on window OS.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

      I've managed to test your code this morning and it works fine under Windows.

      Appreciate your effort.

        You are welcome, Sir!!

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me

      Thanks I'll give that a go.