Perl directories - How to work on each file in a directory

Perl file and directory FAQ: 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 Perl code that prints a listing of every file in the current directory:

#!/usr/bin/perl -w

# a perl file example

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

foreach $file (@files) {
  # put your perl code here
  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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.