Perl directory list - List all files that match a filename pattern

Summary: A quick Perl tip on how to list all files in a directory that match a given filename pattern, i.e., using the Perl filename "glob" pattern-matching syntax.

As a quick tip today, here's some sample Perl code that prints a listing of every file in the current directory that ends with the filename extension .html:

#!/usr/bin/perl -w

opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);

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

As you can see, this Perl code looks in the current directory; then, as it reads the files in the current directory the grep function only passes the filenames along that match the filename pattern (regex) we supplied.

Perl filename globbing - The filename search pattern

This filename extension search pattern:

\.html$

tells grep to only let the filenames that end with the extension .html to pass through into the array named @files. The "\." represents the decimal character, and the "$" represents the end of the word, so html must be the last four letters of the word, and these letters must come immediately after the decimal.

If you're interested in using this code, all you have is put your logic inside of the foreach loop. Good luck!

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.