Processing All Files in a Directory

Problem

You want to do something to each file in a particular directory.

Solution

Use opendir to open the directory and then readdir to retrieve every filename:

opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
while (defined($file = readdir(DIR))) {
    # do something with "$dirname/$file"
}
closedir(DIR);

Discussion

The opendir, readdir, and closedir functions operate on directories as open, < >, and close operate on files. Both use handles, but the directory handles used by opendir and friends are different from the file handles used by open and friends. In particular, you can’t use < > on a directory handle.

In scalar context, readdir returns the next filename in the directory until it reaches the end of the directory when it returns undef. In list context it returns the rest of the filenames in the directory or an empty list if there were no files left. As explained in the Introduction, the filenames returned by readdir do not include the directory name. When you work with the filenames returned by readdir, you must either move to the right directory first or prepend the directory to the filename.

This shows one way of prepending:

$dir = "/usr/local/bin";
print "Text files in $dir are:\n";
opendir(BIN, $dir) or die "Can't open $dir: $!";
while( defined ($file = readdir BIN) ) {
    print "$file\n" if -T "$dir/$file";
}
closedir(BIN);

We test $file with defined because simply saying while ($file = readdir BIN) would only be testing truth and ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.