Directory Handles
Another way to get a list of names from a given directory is with
a directory handle. A directory handle looks and
acts like a filehandle. You open it (with opendir instead of open), you read from it (with readdir instead of readline), and you close it (with closedir instead of close). But instead of reading the
contents of a file, you’re reading the
names of files (and other things) in a directory.
For example:
my $dir_to_process = "/etc";
opendir DH, $dir_to_process or die "Cannot open $dir_to_process: $!";
foreach $file (readdir DH) {
print "one file in $dir_to_process is $file\n";
}
closedir DH;Like filehandles, directory handles are automatically closed at the end of the program or if the directory handle is reopened onto another directory.
Unlike globbing, which in older versions of Perl fired off a separate process, a directory handle never fires off another process. So it makes them more efficient for applications that demand every ounce of power from the machine. However, it’s also a lower-level operation, meaning that we have to do more of the work ourselves.
For example, the names are returned in no particular
order.[†] And the list includes all files, not just those matching a
particular pattern (like *.pm from
our globbing examples). It is also includes the dot files, and
particularly the dot and dot-dot entries.[‡] So, if we wanted only the pm-ending
files, we could use a skip-over function inside the loop:
while ($name = readdir DIR) { next unless $name ...