Perl - How to process every file in a directory that matches a pattern

Perl FAQ: "How can I process every file in a directory that matches a certain filename pattern?"

There are several ways to do this, but I normally use the glob function, because I can remember the syntax pretty easily.

Let's look at a couple of glob examples.

Using the glob operator

You can use the glob operator to get a list of all files in the current directory like this:

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

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

Listing files by their filename extension

Or you can modify your glob pattern to get a list of all the filenames that end with .pl, like this:

# look for all *.pl files
@files = glob("*.pl");

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

Listing files that match any pattern

Finally, the wildcard characters you use don't have to be limited to just the filename extension. You can use them anywhere in a filename, like this example:

# look for files whose filename contains the characters "ep"
@files = glob("*ep*");

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