Learn Perl: Perl Q&A: How do I generate a list of all .html files in a directory?
Developer's Daily Perl Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Perl
Education
Perl Q&A


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

Answer:

This question is similar to another Q&A article, 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.

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!

 

Copyright © 1998 DevDaily Interactive, Inc.
All Rights Reserved.