Chapter 7. File Access
Introduction
I the heir of all ages, in the foremost files of time.
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, 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 in the file /usr/local/widgets/data that
contain the word "blue"
:
open(INPUT, "< /usr/local/widgets/data") or die "Couldn't open /usr/local/widgets/data for reading: $!\n"; while (<INPUT>) { print if /blue/; } close(INPUT);
Getting a Handle on the File
Central to
Perl’s file access is the filehandle, like
INPUT in the preceding program. This is a symbol you use to represent
the file when you read and write. Because filehandles aren’t
variables (they don’t have a $
,
@
, or %
type marker on their
names—but they are part of Perl’s symbol table just as
subroutines and variables are), storing filehandles in variables and
passing them to subroutines won’t always work. You should use
the odd-looking
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.