Setting the Default I/O Layers (Perl Cookbook, 2nd Edition)

## 8.19. Setting the Default I/O Layers

### 8.19.1. Problem

You want to ensure all files opened by your program use a particular set of I/O layers. For example, you know that every file will contain UTF-8 data.

### 8.19.2. Solution

Use the `open` pragma:

>     use open IO => ":raw:utf8";

### 8.19.3. Discussion

You can easily specify I/O layers when you open a filehandle directly, but that doesn't help you when the filehandle is opened by someone else's code (possibly even the Perl core). The `open` pragma lets you specify a default set of layers for every `open` that doesn't specify its own layers.

The `open` module also offers separate `IN` and `OUT` control for input and output handles. For example, to read bytes and emit UTF-8:

>     use open "IN" => ":bytes", "OUT" => ":utf8";

The `:std` option tells `open` to apply the input and output layers to `STDIN` and `STDOUT`/`STDERR`. For example, the following code makes input handles read Greek (ISO 8859-7) and output handles write in the UTF-8 Unicode encoding. Then it applies the same layers to `STDIN`, `STDOUT`, and `STDERR`:

>     use open "IN" => ":encoding(Greek)",     # reading Greek
>              "OUT" => ":utf8",               # writing 8-bit data in Unicode UTF-8,
>              ":std";                         # STDIN is Greek,

### 8.19.4. See Also

The documentation for the standard `open` pragma; Recipe 8.12 and Recipe 8.19

Copyright © 2003 O'Reilly & Associates. All rights reserved.