How do I do (fill in the blank) for each file in a directory?

Question: How do I do (fill in the blank) for each file in a directory?

Answer:

I'm often asked a question like this: "Using Perl, 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. As a system administrator using Perl, 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 an example of some Perl 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?

What's Related



devdaily logo