1PERLOPENTUT(1)         Perl Programmers Reference Guide         PERLOPENTUT(1)
2
3
4

NAME

6       perlopentut - simple recipes for opening files and pipes in Perl
7

DESCRIPTION

9       Whenever you do I/O on a file in Perl, you do so through what in Perl
10       is called a filehandle.  A filehandle is an internal name for an
11       external file.  It is the job of the "open" function to make the
12       association between the internal name and the external name, and it is
13       the job of the "close" function to break that association.
14
15       For your convenience, Perl sets up a few special filehandles that are
16       already open when you run.  These include "STDIN", "STDOUT", "STDERR",
17       and "ARGV".  Since those are pre-opened, you can use them right away
18       without having to go to the trouble of opening them yourself:
19
20           print STDERR "This is a debugging message.\n";
21
22           print STDOUT "Please enter something: ";
23           $response = <STDIN> // die "how come no input?";
24           print STDOUT "Thank you!\n";
25
26           while (<ARGV>) { ... }
27
28       As you see from those examples, "STDOUT" and "STDERR" are output
29       handles, and "STDIN" and "ARGV" are input handles.  They are in all
30       capital letters because they are reserved to Perl, much like the @ARGV
31       array and the %ENV hash are.  Their external associations were set up
32       by your shell.
33
34       You will need to open every other filehandle on your own. Although
35       there are many variants, the most common way to call Perl's open()
36       function is with three arguments and one return value:
37
38       "    OK = open(HANDLE, MODE, PATHNAME)"
39
40       Where:
41
42       OK  will be some defined value if the open succeeds, but "undef" if it
43           fails;
44
45       HANDLE
46           should be an undefined scalar variable to be filled in by the
47           "open" function if it succeeds;
48
49       MODE
50           is the access mode and the encoding format to open the file with;
51
52       PATHNAME
53           is the external name of the file you want opened.
54
55       Most of the complexity of the "open" function lies in the many possible
56       values that the MODE parameter can take on.
57
58       One last thing before we show you how to open files: opening files does
59       not (usually) automatically lock them in Perl.  See perlfaq5 for how to
60       lock.
61

Opening Text Files

63   Opening Text Files for Reading
64       If you want to read from a text file, first open it in read-only mode
65       like this:
66
67           my $filename = "/some/path/to/a/textfile/goes/here";
68           my $encoding = ":encoding(UTF-8)";
69           my $handle   = undef;     # this will be filled in on success
70
71           open($handle, "< $encoding", $filename)
72               || die "$0: can't open $filename for reading: $!";
73
74       As with the shell, in Perl the "<" is used to open the file in read-
75       only mode.  If it succeeds, Perl allocates a brand new filehandle for
76       you and fills in your previously undefined $handle argument with a
77       reference to that handle.
78
79       Now you may use functions like "readline", "read", "getc", and
80       "sysread" on that handle.  Probably the most common input function is
81       the one that looks like an operator:
82
83           $line = readline($handle);
84           $line = <$handle>;          # same thing
85
86       Because the "readline" function returns "undef" at end of file or upon
87       error, you will sometimes see it used this way:
88
89           $line = <$handle>;
90           if (defined $line) {
91               # do something with $line
92           }
93           else {
94               # $line is not valid, so skip it
95           }
96
97       You can also just quickly "die" on an undefined value this way:
98
99           $line = <$handle> // die "no input found";
100
101       However, if hitting EOF is an expected and normal event, you do not
102       want to exit simply because you have run out of input.  Instead, you
103       probably just want to exit an input loop.  You can then test to see if
104       an actual error has caused the loop to terminate, and act accordingly:
105
106           while (<$handle>) {
107               # do something with data in $_
108           }
109           if ($!) {
110               die "unexpected error while reading from $filename: $!";
111           }
112
113       A Note on Encodings: Having to specify the text encoding every time
114       might seem a bit of a bother.  To set up a default encoding for "open"
115       so that you don't have to supply it each time, you can use the "open"
116       pragma:
117
118           use open qw< :encoding(UTF-8) >;
119
120       Once you've done that, you can safely omit the encoding part of the
121       open mode:
122
123           open($handle, "<", $filename)
124               || die "$0: can't open $filename for reading: $!";
125
126       But never use the bare "<" without having set up a default encoding
127       first.  Otherwise, Perl cannot know which of the many, many, many
128       possible flavors of text file you have, and Perl will have no idea how
129       to correctly map the data in your file into actual characters it can
130       work with.  Other common encoding formats including "ASCII",
131       "ISO-8859-1", "ISO-8859-15", "Windows-1252", "MacRoman", and even
132       "UTF-16LE".  See perlunitut for more about encodings.
133
134   Opening Text Files for Writing
135       When you want to write to a file, you first have to decide what to do
136       about any existing contents of that file.  You have two basic choices
137       here: to preserve or to clobber.
138
139       If you want to preserve any existing contents, then you want to open
140       the file in append mode.  As in the shell, in Perl you use ">>" to open
141       an existing file in append mode.  ">>" creates the file if it does not
142       already exist.
143
144           my $handle   = undef;
145           my $filename = "/some/path/to/a/textfile/goes/here";
146           my $encoding = ":encoding(UTF-8)";
147
148           open($handle, ">> $encoding", $filename)
149               || die "$0: can't open $filename for appending: $!";
150
151       Now you can write to that filehandle using any of "print", "printf",
152       "say", "write", or "syswrite".
153
154       As noted above, if the file does not already exist, then the append-
155       mode open will create it for you.  But if the file does already exist,
156       its contents are safe from harm because you will be adding your new
157       text past the end of the old text.
158
159       On the other hand, sometimes you want to clobber whatever might already
160       be there.  To empty out a file before you start writing to it, you can
161       open it in write-only mode:
162
163           my $handle   = undef;
164           my $filename = "/some/path/to/a/textfile/goes/here";
165           my $encoding = ":encoding(UTF-8)";
166
167           open($handle, "> $encoding", $filename)
168               || die "$0: can't open $filename in write-open mode: $!";
169
170       Here again Perl works just like the shell in that the ">" clobbers an
171       existing file.
172
173       As with the append mode, when you open a file in write-only mode, you
174       can now write to that filehandle using any of "print", "printf", "say",
175       "write", or "syswrite".
176
177       What about read-write mode?  You should probably pretend it doesn't
178       exist, because opening text files in read-write mode is unlikely to do
179       what you would like.  See perlfaq5 for details.
180

Opening Binary Files

182       If the file to be opened contains binary data instead of text
183       characters, then the "MODE" argument to "open" is a little different.
184       Instead of specifying the encoding, you tell Perl that your data are in
185       raw bytes.
186
187           my $filename = "/some/path/to/a/binary/file/goes/here";
188           my $encoding = ":raw :bytes"
189           my $handle   = undef;     # this will be filled in on success
190
191       And then open as before, choosing "<", ">>", or ">" as needed:
192
193           open($handle, "< $encoding", $filename)
194               || die "$0: can't open $filename for reading: $!";
195
196           open($handle, ">> $encoding", $filename)
197               || die "$0: can't open $filename for appending: $!";
198
199           open($handle, "> $encoding", $filename)
200               || die "$0: can't open $filename in write-open mode: $!";
201
202       Alternately, you can change to binary mode on an existing handle this
203       way:
204
205           binmode($handle)    || die "cannot binmode handle";
206
207       This is especially handy for the handles that Perl has already opened
208       for you.
209
210           binmode(STDIN)      || die "cannot binmode STDIN";
211           binmode(STDOUT)     || die "cannot binmode STDOUT";
212
213       You can also pass "binmode" an explicit encoding to change it on the
214       fly.  This isn't exactly "binary" mode, but we still use "binmode" to
215       do it:
216
217         binmode(STDIN,  ":encoding(MacRoman)") || die "cannot binmode STDIN";
218         binmode(STDOUT, ":encoding(UTF-8)")    || die "cannot binmode STDOUT";
219
220       Once you have your binary file properly opened in the right mode, you
221       can use all the same Perl I/O functions as you used on text files.
222       However, you may wish to use the fixed-size "read" instead of the
223       variable-sized "readline" for your input.
224
225       Here's an example of how to copy a binary file:
226
227           my $BUFSIZ   = 64 * (2 ** 10);
228           my $name_in  = "/some/input/file";
229           my $name_out = "/some/output/flie";
230
231           my($in_fh, $out_fh, $buffer);
232
233           open($in_fh,  "<", $name_in)
234               || die "$0: cannot open $name_in for reading: $!";
235           open($out_fh, ">", $name_out)
236               || die "$0: cannot open $name_out for writing: $!";
237
238           for my $fh ($in_fh, $out_fh)  {
239               binmode($fh)               || die "binmode failed";
240           }
241
242           while (read($in_fh, $buffer, $BUFSIZ)) {
243               unless (print $out_fh $buffer) {
244                   die "couldn't write to $name_out: $!";
245               }
246           }
247
248           close($in_fh)       || die "couldn't close $name_in: $!";
249           close($out_fh)      || die "couldn't close $name_out: $!";
250

Opening Pipes

252       To be announced.
253

Low-level File Opens via sysopen

255       To be announced.  Or deleted.
256

SEE ALSO

258       To be announced.
259
261       Copyright 2013 Tom Christiansen.
262
263       This documentation is free; you can redistribute it and/or modify it
264       under the same terms as Perl itself.
265
266
267
268perl v5.26.3                      2018-03-01                    PERLOPENTUT(1)
Impressum