Perl - How to process every file in a directory

A common Perl FAQ is "How do I do (something) for every file in a directory?"

Here's some sample code that will show you how to loop through each file in a directory:

$dirname = '.';
opendir(DIR, $dirname) or die "Could not open $dirname\n";

while ($filename = readdir(DIR)) {
  print "$filename\n";
}

closedir(DIR);

In this case my directory was the current directory, represented by ".", but it could have been another directory, like /tmp, or any other directory.

Notes about directories

As you might guess from looking at that code, the opendir, readdir, and closedir are the directory equivalents of the file operators open, <>, and close, respectively.

Test to see if it's really a file

You'll probably also want to test that what you get back from the readdir operator is actually a file, and not something else, like a directory, a link, or a pipe. Here's a simple way to test that each "file" is really a plain file:

$dirname = '.';
opendir(DIR, $dirname) or die "Could not open $dirname\n";

while ($filename = readdir(DIR)) {
  print "$filename\n" if -f $filename;
}

closedir(DIR);

Note that all I did there was add this test to the print line:

if -f $filename

where the -f operator determines whether the file is a regular file.

Using the glob operator

Finally, you can also use the glob operator if you prefer, something like this code sample:

@files = glob("*.*");

foreach $file (@files) {
  print "$file\n" if -f $file;
}

I'll write more about the glob operator in other tutorials, but hopefully that's enough to whet your appetite.