Chapter 4. Handling Files in Perl
IO Introduction > STDOUT > Writing Files > STDIN > Reading Files > Reading 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";
}
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:
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
____
Questions? Feedback?
Email me your
comments!
Like the course?
Please rate the site here
Copyright 2003-2007 Michael Gossland and
Associates. All rights reserved.
|