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). Instead of reading the contents of a file, you’re reading the names of files (and other things) in a directory as in this 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, which makes it more efficient for applications that demand every ounce of power from the machine. However, it’s 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.[278] The list includes all files, not just those matching a particular pattern (such as *.pm from our globbing examples). And the list includes all files, especially the dot files and the dot and dot-dot entries.[279] So, if we wanted only the pm-ending files, we could use a skip-over function inside the loop:
while ($name = readdir DIR) { next ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access