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:
sub is_empty_dir
{
my $path = shift();
my $rv = 1;
opendir DIR, $path or die "$path: $!\n";
while (my $entry = readdir(DIR))
{
next if ($entry eq "." or $entry eq "..");
# Entry found beneath $path, directory is not empty
$rv = 0;
last;
}
closedir(DIR);
return $rv;
}
Download this subroutine.