Learn Perl: Perl Q&A: How do I do fill-in-the-blank for every file 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 do fill_in_the_blank for each file in a directory?

Answer:

I'm often asked a question like this: "How do I do fill_in_the_blank for each file in a directory?"

I'll leave the "fill in the blank" part up to you. I've seen the need to do many things to every file in a directory - print each file, change one line in every file, rename the file - whatever. The cool part is that it's very easy to accomplish these tasks with Perl.

Here's a snippet of code that just prints a listing of every file in the current directory:


#!/usr/bin/perl -w

opendir(DIR, ".");
@files = readdir(DIR);
closedir(DIR);

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

In place of the print code I've shown inside the foreach statement, you can embed your own logic to manipulate each $file as it comes through the loop.

Final Note:  If you're interested in operating only on certain files in a directory, such as files ending with the filename extension .html, take a look at our companion article, How do I generate a list of all .html files in a directory?

 

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