Perl (Scripting) - Determine if a directory is empty

by
Jeremy Canfield |
Updated: June 24 2020
| Perl (Scripting) articles
Let's say the /tmp directory contains two non-hidden files, foo.txt and bar.txt.
ls -lisa /tmp
8409154 8 drwxrwxrwt. 49 root root 4096 Jun 24 04:08 .
64 0 dr-xr-xr-x. 17 root root 224 Jun 24 04:00 ..
8422986 4 -rw-r--r--. 1 root root 330 Jun 23 22:55 foo.txt
8422988 4 -rw-r--r--. 1 root root 2835 Jun 18 03:21 bar.txt
The following Perl script will return the number of non-hidden objects in the /tmp directory. In this example, the script will print "2". If the /tmp directory were empty, the script would print "0".
#!/usr/bin/perl
use strict;
use warnings;
opendir(my $dh, "/tmp");
print scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh));
Let's say you want to use this as a subroutine.
If directory is empty (care of this Stack Overflow post).
sub directory_is_empty {
my $directory = shift;
opendir(my $dh, $directory);
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh));
}
You would then do something like this to store the count of non-hidden objects in the directory.
my $count = directory_is_empty("/path/to/directory");
Did you find this article helpful?
If so, consider buying me a coffee over at