Skip to Content
Perl Cookbook, 2nd Edition
book

Perl Cookbook, 2nd Edition

by Tom Christiansen, Nathan Torkington
August 2003
Intermediate to advanced content levelIntermediate to advanced
964 pages
23h 24m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook, 2nd Edition

Chapter 7. File Access

I the heir of all ages, in the foremost files of time.

Alfred, Lord Tennyson, Locksley Hall

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Cookbook

Perl Cookbook

Tom Christiansen, Nathan Torkington
Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant

Publisher Resources

ISBN: 0596003137Supplemental ContentErrata Page