Chapter 7. File Access
I the heir of all ages, in the foremost files of time.
Introduction
Nothing is more central to data processing than the file. As with everything else in Perl, easy things are easy and hard things are possible. Common tasks (opening files, reading data, writing data) use simple I/O functions and operators, whereas fancier functions do hard things like non-blocking I/O and file locking.
This chapter deals with the mechanics of file access: opening a file, telling subroutines which files to work with, locking files, and so on. Chapter 8 deals with techniques for working with the contents of a file: reading, writing, shuffling lines, and other operations you can do once you have access to the file.
Here’s Perl code for printing all lines from the file
/usr/local/widgets/data that contain the word
"blue“:
open(INPUT, "<", "/acme/widgets/data")
or die "Couldn't open /acme/widgets/data for reading: $!\n";
while (<INPUT>) {
print if /blue/;
}
close(INPUT);Getting a Handle on the File
Central to file access in Perl is the
filehandle, like INPUT in the previous code example.
Filehandles are symbols inside your Perl program that you associate
with an external file, usually using the open function. Whenever your program
performs an input or output operation, it provides that operation with
an internal filehandle, not an external filename. It’s the job of
open to make that association, and
of close to break it. Actually, any of several functions ...