Mike Gossland’s Perl Tutorial Course for Windows

Chapter 4. Handling Files in Perl

IO Introduction > STDOUT > Writing Files > STDIN > Reading FilesReading Directories > Editing Files > Recursive Editing

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.

Next Page

Search this site or the web:

just this site the whole web

Questions? Feedback?

Email me your comments!