Main Content

Processing all files in a directory - Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-10-11 07:25:48 - Graham Ellis

From this week's Perl course:

opendir(DH, ".");
while ($igot = readdir(DH)) {
  next if ($igot =~ /^\.{1,2}$/);
  print "igot $igot\n";
}


You'll notice that I have used a regular expression to check for files called dot and dot-dot, which are the current and parent directory, as I typically would NOT want to process each of them in my loop.

Other alternatives ... this is Perl so "There is more than one way" ... include:

@files = glob("*");

@files = <*>

@files = `ls`

but although each of these is shorter, they are not recommended for heavy directory traversal applications - in each case, they return you a sorted list of names and that sorting can be useful for a single directory, but wasteful in a heavier application that's going through a large number of directories.


Once you are traversing a directory, you can do all sorts of things - use operators such as -d to find out what is a subdirectory, and -s to find the size of individual contents, for example.

If you want to find the biggest file in or below a directory (perhaps you're running out of disc space?), we have a sample program here from our Perl for larger projects course. The illustration with accompanies this article shows delegates on a private Perl training course, running at their offices in the UK.