Subscribe to the RSS feed for the devdaily.com blog
Page not found (404 error) | alvinalexander.com

Page not found (404 error)

I’m sorry, the URL you are looking for can't be found.

This may be because I’ve made several significant changes to the website lately. If you want to take a few moments to search for the document you were looking for, you can try the Search Page here.

(I am trying to fix all the links I have broken, but it takes time.)

Thank you for your patience, and have a nice day!

Alvin Alexander
Owner, Editor, Link-breaker, Repairman,
AlvinAlexander.com


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