Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect empty directory with Perl

What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{ 
    die "\n$gAppsDir is not accessible or does not exist.\n"; 
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{ 
    die "\n$gAppsDir is not accessible or does not exist.\n"; 
}

These above, do not work properly to tell me that the folder is empty. Thanks!


Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory"; 
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
like image 602
Christopher Peterson Avatar asked Dec 20 '10 20:12

Christopher Peterson


2 Answers

A little verbose for clarity, but:

sub is_folder_empty {
    my $dirname = shift;
    opendir(my $dh, $dirname) or die "Not a directory";
    return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
}

Then you can do:

if (is_folder_empty($your_dir)) {
    ....
}
like image 104
Brad Fitzpatrick Avatar answered Oct 17 '22 10:10

Brad Fitzpatrick


Using grep { ! /^[.][.]?\z/ } readdir $dir_h can be problematic for performance in case the check is done many times and some directories may have many files.

It would be better to short-circuit the moment a directory entry other than . or .. is found.

On Windows XP with ActiveState perl 5.10.1, the following sub seems to be twice as fast as the grep approach on my $HOME with 100 entries:

sub is_dir_empty {
    my ($dir) = @_;

    opendir my $h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $h) ) {
        return unless $entry =~ /^[.][.]?\z/;
    }

    return 1;
}
like image 5
Sinan Ünür Avatar answered Oct 17 '22 11:10

Sinan Ünür