O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. File Access

Introduction

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

Alfred, Lord Tennyson, Locksley Hall

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required