Perl directory list - How do to list all .html files in a directory

Perl directory list FAQ: How do I generate a list of all .html files in a directory?

Answer: This question is similar to another Perl FAQ, How do I do (fill in the blank) for each file in a directory?

The answer is, in fact, very similar. The only thing you need to do differently is to put a search pattern around the readdir statement.

A Perl directory list example

Here's some sample Perl source code that just prints a listing of every file in the current directory that ends with the extension .html:

#!/usr/bin/perl -w

# create a list of all *.html files in
# the current directory
opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);

# print all the filenames in our array
foreach $file (@files) {
   print "$file\n";
}

As you can see, this source code example 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 search pattern. The 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!