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

By Alvin J. Alexander, devdaily.com

Here's a snippet of code that just prints a listing of every file in the current directory that ends with the 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 code snippet 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!


devdaily logo