Mike Gossland's Perl Tutorial Course for Windows


IO Introduction | STDOUT | Writing to Files | Reading from Files | Reading Directories | Editing File Contents | Recursive Editing


Chapter 4. Handling Files in Perl

Reading Directories

Often you'll want to do a directory listing to find out what files are present in a directory. It's easy with the opendir, readdir, and closedir functions. For these you use a directoryhandle which is quite a bit like a filehandle.

You can use a scalar context to read one filename at a time:

opendir DIR, ".";     # . is the current directory
while ( $filename = readdir(DIR) ) {
  print $filename , "\n";
}
closedir DIR;

Or you could use an array context and read the files into an array as in the next example. You don't have to specify the current directory. You could specify some other path: 

opendir DIR, "c:/";
@files = readdir(DIR);
closedir DIR;
print map { "$_\n" } sort  @files;

This last line sorts the @files array into ascii-based order before printing the files, one per line.

We are now ready to begin the section on editing files.