perlfiledirectory

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; }

Solution

  • 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)) {
        ....
    }