Opening files#

Everything a Perl program does with a file, a pipe, or a buffer goes through a filehandle. This chapter is a recipe collection for the open built-in: how to read, write, append, pipe, encode, and recover from errors — each recipe small enough to copy, each warning pinned to the line that bites.

The pre-opened handles — STDIN, STDOUT, STDERR, ARGV — are available from the first line of a program:

print STDERR "debug: entered phase 2\n";
print STDOUT "name? ";
my $name = <STDIN> // die "no input";
while (<ARGV>) { ... }

Every other handle you open yourself. The modern form is always three arguments — handle, mode, target — and the handle is a lexical scalar:

open my $fh, "<", $path    or die "open $path: $!";

Read that form until it is muscle memory. Everything else on the following pages is a variation on it.

What this chapter does not cover#

  • Locking. Opening does not lock. See flock when you need advisory locking across processes.

  • Low-level descriptor control. For O_EXCL, O_NONBLOCK, and explicit permission bits, see sysopen.

  • Directory iteration. open is for files, pipes, and in-memory buffers. Directory reading uses opendir / readdir.

Where to go next#