Perl: Checking a directory for emptiness

If you need to check a directory for emptiness within a Perl script, it's best to use a set of Perl's builtin functions. Once a directory handle is obtained by calling opendir, iterate over the directory's entries using readdir and be sure to ignore the reference-only entries ("." & ".."). If any other entry is found, the directory in question is not empty.

The following subroutine should work an any Unix-like system:

    1 sub is_empty_dir
    2 {
    3     my $path = shift();
    4     my $rv     = 1;
    5 
    6     opendir DIR, $path or die "$path: $!\n";
    7 
    8     while (my $entry = readdir(DIR))
    9     {
   10         next if ($entry eq "." or $entry eq "..");
   11 
   12         # Entry found beneath $path, directory is not empty
   13         $rv = 0;
   14 
   15         last;
   16     }
   17 
   18     closedir(DIR);
   19 
   20     return $rv;
   21 }

Download