```{index} single: open, single: filehandle, single: I/O; opening files ``` # 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. ```{index} single: STDIN, single: STDOUT, single: STDERR, single: ARGV, single: pre-opened handles ``` The pre-opened handles — `STDIN`, `STDOUT`, `STDERR`, `ARGV` — are available from the first line of a program: ```perl print STDERR "debug: entered phase 2\n"; print STDOUT "name? "; my $name = // die "no input"; while () { ... } ``` ```{index} single: open; 3-arg form, single: lexical filehandle ``` Every other handle you open yourself. The modern form is always three arguments — handle, mode, target — and the handle is a lexical scalar: ```perl 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 ```{index} single: flock, single: sysopen, single: opendir, single: readdir, single: O_EXCL, single: O_NONBLOCK ``` - **Locking.** Opening does not lock. See [`flock`](../../p5/core/perlfunc/flock) when you need advisory locking across processes. - **Low-level descriptor control.** For `O_EXCL`, `O_NONBLOCK`, and explicit permission bits, see [`sysopen`](../../p5/core/perlfunc/sysopen). - **Directory iteration.** `open` is for files, pipes, and in-memory buffers. Directory reading uses `opendir` / `readdir`. ## Where to go next ```{toctree} :maxdepth: 1 basic-files encoding-and-layers pipes in-memory handling-errors ``` ## Reference cross-links Every recipe here links into the per-built-in reference when a function's full behaviour matters: - [`open`](../../p5/core/perlfunc/open) — full argument shape, all modes - [`close`](../../p5/core/perlfunc/close) — closing and checking the result - [`binmode`](../../p5/core/perlfunc/binmode) — layers after the fact - [`readline`](../../p5/core/perlfunc/readline) — the function behind `<$fh>` - [`sysopen`](../../p5/core/perlfunc/sysopen) — low-level open with flag bits - [`sysread`](../../p5/core/perlfunc/sysread) — unbuffered read - [`syswrite`](../../p5/core/perlfunc/syswrite) — unbuffered write