Debian Codegraph @

upstream/mageia-cauldron/man1/perlopentut.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLOPENTUT 1"
61 .TH PERLOPENTUT 1 2025-06-24 "perl v5.42.0" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlopentut \- simple recipes for opening files and pipes in Perl
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 Whenever you do I/O on a file in Perl, you do so through what in Perl is
71 called a \fBfilehandle\fR. A filehandle is an internal name for an external
72 file. It is the job of the \f(CW\*(C`open\*(C'\fR function to make the association
73 between the internal name and the external name, and it is the job
74 of the \f(CW\*(C`close\*(C'\fR function to break that association.
75 .PP
76 For your convenience, Perl sets up a few special filehandles that are
77 already open when you run. These include \f(CW\*(C`STDIN\*(C'\fR, \f(CW\*(C`STDOUT\*(C'\fR, \f(CW\*(C`STDERR\*(C'\fR,
78 and \f(CW\*(C`ARGV\*(C'\fR. Since those are pre\-opened, you can use them right away
79 without having to go to the trouble of opening them yourself:
80 .PP
81 .Vb 1
82 \& print STDERR "This is a debugging message.\en";
83 \&
84 \& print STDOUT "Please enter something: ";
85 \& $response = <STDIN> // die "how come no input?";
86 \& print STDOUT "Thank you!\en";
87 \&
88 \& while (<ARGV>) { ... }
89 .Ve
90 .PP
91 As you see from those examples, \f(CW\*(C`STDOUT\*(C'\fR and \f(CW\*(C`STDERR\*(C'\fR are output
92 handles, and \f(CW\*(C`STDIN\*(C'\fR and \f(CW\*(C`ARGV\*(C'\fR are input handles. They are
93 in all capital letters because they are reserved to Perl, much
94 like the \f(CW@ARGV\fR array and the \f(CW%ENV\fR hash are. Their external
95 associations were set up by your shell.
96 .PP
97 You will need to open every other filehandle on your own. Although there
98 are many variants, the most common way to call Perl\*(Aqs \fBopen()\fR function
99 is with three arguments and one return value:
100 .PP
101 \&\f(CW\*(C` \fR\f(CIOK\fR\f(CW = open(\fR\f(CIHANDLE\fR\f(CW, \fR\f(CIMODE\fR\f(CW, \fR\f(CIPATHNAME\fR\f(CW)\*(C'\fR
102 .PP
103 Where:
104 .IP \fIOK\fR 4
105 .IX Item "OK"
106 will be some defined value if the open succeeds, but
107 \&\f(CW\*(C`undef\*(C'\fR if it fails;
108 .IP \fIHANDLE\fR 4
109 .IX Item "HANDLE"
110 should be an undefined scalar variable to be filled in by the
111 \&\f(CW\*(C`open\*(C'\fR function if it succeeds;
112 .IP \fIMODE\fR 4
113 .IX Item "MODE"
114 is the access mode and the encoding format to open the file with;
115 .IP \fIPATHNAME\fR 4
116 .IX Item "PATHNAME"
117 is the external name of the file you want opened.
118 .PP
119 Most of the complexity of the \f(CW\*(C`open\*(C'\fR function lies in the many
120 possible values that the \fIMODE\fR parameter can take on.
121 .PP
122 One last thing before we show you how to open files: opening
123 files does not (usually) automatically lock them in Perl. See
124 perlfaq5 for how to lock.
125 .SH "Opening Text Files"
126 .IX Header "Opening Text Files"
127 .SS "Opening Text Files for Reading"
128 .IX Subsection "Opening Text Files for Reading"
129 If you want to read from a text file, first open it in
130 read\-only mode like this:
131 .PP
132 .Vb 3
133 \& my $filename = "/some/path/to/a/textfile/goes/here";
134 \& my $encoding = ":encoding(UTF\-8)";
135 \& my $handle = undef; # this will be filled in on success
136 \&
137 \& open($handle, "< $encoding", $filename)
138 \& || die "$0: can\*(Aqt open $filename for reading: $!";
139 .Ve
140 .PP
141 As with the shell, in Perl the \f(CW"<"\fR is used to open the file in
142 read\-only mode. If it succeeds, Perl allocates a brand new filehandle for
143 you and fills in your previously undefined \f(CW$handle\fR argument with a
144 reference to that handle.
145 .PP
146 Now you may use functions like \f(CW\*(C`readline\*(C'\fR, \f(CW\*(C`read\*(C'\fR, \f(CW\*(C`getc\*(C'\fR, and
147 \&\f(CW\*(C`sysread\*(C'\fR on that handle. Probably the most common input function
148 is the one that looks like an operator:
149 .PP
150 .Vb 2
151 \& $line = readline($handle);
152 \& $line = <$handle>; # same thing
153 .Ve
154 .PP
155 Because the \f(CW\*(C`readline\*(C'\fR function returns \f(CW\*(C`undef\*(C'\fR at end of file or
156 upon error, you will sometimes see it used this way:
157 .PP
158 .Vb 7
159 \& $line = <$handle>;
160 \& if (defined $line) {
161 \& # do something with $line
162 \& }
163 \& else {
164 \& # $line is not valid, so skip it
165 \& }
166 .Ve
167 .PP
168 You can also just quickly \f(CW\*(C`die\*(C'\fR on an undefined value this way:
169 .PP
170 .Vb 1
171 \& $line = <$handle> // die "no input found";
172 .Ve
173 .PP
174 However, if hitting EOF is an expected and normal event, you do not want to
175 exit simply because you have run out of input. Instead, you probably just want
176 to exit an input loop. You can then test to see if an actual error has caused
177 the loop to terminate, and act accordingly:
178 .PP
179 .Vb 6
180 \& while (<$handle>) {
181 \& # do something with data in $_
182 \& }
183 \& if ($!) {
184 \& die "unexpected error while reading from $filename: $!";
185 \& }
186 .Ve
187 .PP
188 \&\fBA Note on Encodings\fR: Having to specify the text encoding every time
189 might seem a bit of a bother. To set up a default encoding for \f(CW\*(C`open\*(C'\fR so
190 that you don\*(Aqt have to supply it each time, you can use the \f(CW\*(C`open\*(C'\fR pragma:
191 .PP
192 .Vb 1
193 \& use open qw< :encoding(UTF\-8) >;
194 .Ve
195 .PP
196 Once you\*(Aqve done that, you can safely omit the encoding part of the
197 open mode:
198 .PP
199 .Vb 2
200 \& open($handle, "<", $filename)
201 \& || die "$0: can\*(Aqt open $filename for reading: $!";
202 .Ve
203 .PP
204 But never use the bare \f(CW"<"\fR without having set up a default encoding
205 first. Otherwise, Perl cannot know which of the many, many, many possible
206 flavors of text file you have, and Perl will have no idea how to correctly
207 map the data in your file into actual characters it can work with. Other
208 common encoding formats including \f(CW"ASCII"\fR, \f(CW"ISO\-8859\-1"\fR,
209 \&\f(CW"ISO\-8859\-15"\fR, \f(CW"Windows\-1252"\fR, \f(CW"MacRoman"\fR, and even \f(CW"UTF\-16LE"\fR.
210 See perlunitut for more about encodings.
211 .SS "Opening Text Files for Writing"
212 .IX Subsection "Opening Text Files for Writing"
213 When you want to write to a file, you first have to decide what to do about
214 any existing contents of that file. You have two basic choices here: to
215 preserve or to clobber.
216 .PP
217 If you want to preserve any existing contents, then you want to open the file
218 in append mode. As in the shell, in Perl you use \f(CW">>"\fR to open an
219 existing file in append mode. \f(CW">>"\fR creates the file if it does not
220 already exist.
221 .PP
222 .Vb 3
223 \& my $handle = undef;
224 \& my $filename = "/some/path/to/a/textfile/goes/here";
225 \& my $encoding = ":encoding(UTF\-8)";
226 \&
227 \& open($handle, ">> $encoding", $filename)
228 \& || die "$0: can\*(Aqt open $filename for appending: $!";
229 .Ve
230 .PP
231 Now you can write to that filehandle using any of \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`printf\*(C'\fR,
232 \&\f(CW\*(C`say\*(C'\fR, \f(CW\*(C`write\*(C'\fR, or \f(CW\*(C`syswrite\*(C'\fR.
233 .PP
234 As noted above, if the file does not already exist, then the append\-mode open
235 will create it for you. But if the file does already exist, its contents are
236 safe from harm because you will be adding your new text past the end of the
237 old text.
238 .PP
239 On the other hand, sometimes you want to clobber whatever might already be
240 there. To empty out a file before you start writing to it, you can open it
241 in write\-only mode:
242 .PP
243 .Vb 3
244 \& my $handle = undef;
245 \& my $filename = "/some/path/to/a/textfile/goes/here";
246 \& my $encoding = ":encoding(UTF\-8)";
247 \&
248 \& open($handle, "> $encoding", $filename)
249 \& || die "$0: can\*(Aqt open $filename in write\-open mode: $!";
250 .Ve
251 .PP
252 Here again Perl works just like the shell in that the \f(CW">"\fR clobbers
253 an existing file.
254 .PP
255 As with the append mode, when you open a file in write\-only mode,
256 you can now write to that filehandle using any of \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`printf\*(C'\fR,
257 \&\f(CW\*(C`say\*(C'\fR, \f(CW\*(C`write\*(C'\fR, or \f(CW\*(C`syswrite\*(C'\fR.
258 .PP
259 What about read\-write mode? You should probably pretend it doesn\*(Aqt exist,
260 because opening text files in read\-write mode is unlikely to do what you
261 would like. See perlfaq5 for details.
262 .SH "Opening Binary Files"
263 .IX Header "Opening Binary Files"
264 If the file to be opened contains binary data instead of text characters,
265 then the \f(CW\*(C`MODE\*(C'\fR argument to \f(CW\*(C`open\*(C'\fR is a little different. Instead of
266 specifying the encoding, you tell Perl that your data are in raw bytes.
267 .PP
268 .Vb 3
269 \& my $filename = "/some/path/to/a/binary/file/goes/here";
270 \& my $encoding = ":raw :bytes"
271 \& my $handle = undef; # this will be filled in on success
272 .Ve
273 .PP
274 And then open as before, choosing \f(CW"<"\fR, \f(CW">>"\fR, or
275 \&\f(CW">"\fR as needed:
276 .PP
277 .Vb 2
278 \& open($handle, "< $encoding", $filename)
279 \& || die "$0: can\*(Aqt open $filename for reading: $!";
280 \&
281 \& open($handle, ">> $encoding", $filename)
282 \& || die "$0: can\*(Aqt open $filename for appending: $!";
283 \&
284 \& open($handle, "> $encoding", $filename)
285 \& || die "$0: can\*(Aqt open $filename in write\-open mode: $!";
286 .Ve
287 .PP
288 Alternately, you can change to binary mode on an existing handle this way:
289 .PP
290 .Vb 1
291 \& binmode($handle) || die "cannot binmode handle";
292 .Ve
293 .PP
294 This is especially handy for the handles that Perl has already opened for you.
295 .PP
296 .Vb 2
297 \& binmode(STDIN) || die "cannot binmode STDIN";
298 \& binmode(STDOUT) || die "cannot binmode STDOUT";
299 .Ve
300 .PP
301 You can also pass \f(CW\*(C`binmode\*(C'\fR an explicit encoding to change it on the fly.
302 This isn\*(Aqt exactly "binary" mode, but we still use \f(CW\*(C`binmode\*(C'\fR to do it:
303 .PP
304 .Vb 2
305 \& binmode(STDIN, ":encoding(MacRoman)") || die "cannot binmode STDIN";
306 \& binmode(STDOUT, ":encoding(UTF\-8)") || die "cannot binmode STDOUT";
307 .Ve
308 .PP
309 Once you have your binary file properly opened in the right mode, you can
310 use all the same Perl I/O functions as you used on text files. However,
311 you may wish to use the fixed\-size \f(CW\*(C`read\*(C'\fR instead of the variable\-sized
312 \&\f(CW\*(C`readline\*(C'\fR for your input.
313 .PP
314 Here\*(Aqs an example of how to copy a binary file:
315 .PP
316 .Vb 3
317 \& my $BUFSIZ = 64 * (2 ** 10);
318 \& my $name_in = "/some/input/file";
319 \& my $name_out = "/some/output/file";
320 \&
321 \& my($in_fh, $out_fh, $buffer);
322 \&
323 \& open($in_fh, "<", $name_in)
324 \& || die "$0: cannot open $name_in for reading: $!";
325 \& open($out_fh, ">", $name_out)
326 \& || die "$0: cannot open $name_out for writing: $!";
327 \&
328 \& for my $fh ($in_fh, $out_fh) {
329 \& binmode($fh) || die "binmode failed";
330 \& }
331 \&
332 \& while (read($in_fh, $buffer, $BUFSIZ)) {
333 \& unless (print $out_fh $buffer) {
334 \& die "couldn\*(Aqt write to $name_out: $!";
335 \& }
336 \& }
337 \&
338 \& close($in_fh) || die "couldn\*(Aqt close $name_in: $!";
339 \& close($out_fh) || die "couldn\*(Aqt close $name_out: $!";
340 .Ve
341 .SH "Opening Pipes"
342 .IX Header "Opening Pipes"
343 Perl also lets you open a filehandle into an external program or shell
344 command rather than into a file. You can do this in order to pass data
345 from your Perl program to an external command for further processing, or
346 to receive data from another program for your own Perl program to
347 process.
348 .PP
349 Filehandles into commands are also known as \fIpipes\fR, since they work on
350 similar inter\-process communication principles as Unix pipelines. Such a
351 filehandle has an active program instead of a static file on its
352 external end, but in every other sense it works just like a more typical
353 file\-based filehandle, with all the techniques discussed earlier in this
354 article just as applicable.
355 .PP
356 As such, you open a pipe using the same \f(CW\*(C`open\*(C'\fR call that you use for
357 opening files, setting the second (\f(CW\*(C`MODE\*(C'\fR) argument to special
358 characters that indicate either an input or an output pipe. Use \f(CW"\-|"\fR for a
359 filehandle that will let your Perl program read data from an external
360 program, and \f(CW"|\-"\fR for a filehandle that will send data to that
361 program instead.
362 .SS "Opening a pipe for reading"
363 .IX Subsection "Opening a pipe for reading"
364 Let\*(Aqs say you\*(Aqd like your Perl program to process data stored in a nearby
365 directory called \f(CW\*(C`unsorted\*(C'\fR, which contains a number of textfiles.
366 You\*(Aqd also like your program to sort all the contents from these files
367 into a single, alphabetically sorted list of unique lines before it
368 starts processing them.
369 .PP
370 You could do this through opening an ordinary filehandle into each of
371 those files, gradually building up an in\-memory array of all the file
372 contents you load this way, and finally sorting and filtering that array
373 when you\*(Aqve run out of files to load. \fIOr\fR, you could offload all that
374 merging and sorting into your operating system\*(Aqs own \f(CW\*(C`sort\*(C'\fR command by
375 opening a pipe directly into its output, and get to work that much
376 faster.
377 .PP
378 Here\*(Aqs how that might look:
379 .PP
380 .Vb 2
381 \& open(my $sort_fh, \*(Aq\-|\*(Aq, \*(Aqsort \-u unsorted/*.txt\*(Aq)
382 \& or die "Couldn\*(Aqt open a pipe into sort: $!";
383 \&
384 \& # And right away, we can start reading sorted lines:
385 \& while (my $line = <$sort_fh>) {
386 \& #
387 \& # ... Do something interesting with each $line here ...
388 \& #
389 \& }
390 .Ve
391 .PP
392 The second argument to \f(CW\*(C`open\*(C'\fR, \f(CW"\-|"\fR, makes it a read\-pipe into a
393 separate program, rather than an ordinary filehandle into a file.
394 .PP
395 Note that the third argument to \f(CW\*(C`open\*(C'\fR is a string containing the
396 program name (\f(CW\*(C`sort\*(C'\fR) plus all its arguments: in this case, \f(CW\*(C`\-u\*(C'\fR to
397 specify unique sort, and then a fileglob specifying the files to sort.
398 The resulting filehandle \f(CW$sort_fh\fR works just like a read\-only (\f(CW"<"\fR) filehandle, and your program can subsequently read data
399 from it as if it were opened onto an ordinary, single file.
400 .SS "Opening a pipe for writing"
401 .IX Subsection "Opening a pipe for writing"
402 Continuing the previous example, let\*(Aqs say that your program has
403 completed its processing, and the results sit in an array called
404 \&\f(CW@processed\fR. You want to print these lines to a file called
405 \&\f(CW\*(C`numbered.txt\*(C'\fR with a neatly formatted column of line\-numbers.
406 .PP
407 Certainly you could write your own code to do this — or, once again,
408 you could kick that work over to another program. In this case, \f(CW\*(C`cat\*(C'\fR,
409 running with its own \f(CW\*(C`\-n\*(C'\fR option to activate line numbering, should do
410 the trick:
411 .PP
412 .Vb 2
413 \& open(my $cat_fh, \*(Aq|\-\*(Aq, \*(Aqcat \-n > numbered.txt\*(Aq)
414 \& or die "Couldn\*(Aqt open a pipe into cat: $!";
415 \&
416 \& for my $line (@processed) {
417 \& print $cat_fh $line;
418 \& }
419 .Ve
420 .PP
421 Here, we use a second \f(CW\*(C`open\*(C'\fR argument of \f(CW"|\-"\fR, signifying that the
422 filehandle assigned to \f(CW$cat_fh\fR should be a write\-pipe. We can then
423 use it just as we would a write\-only ordinary filehandle, including the
424 basic function of \f(CW\*(C`print\*(C'\fR\-ing data to it.
425 .PP
426 Note that the third argument, specifying the command that we wish to
427 pipe to, sets up \f(CW\*(C`cat\*(C'\fR to redirect its output via that \f(CW">"\fR
428 symbol into the file \f(CW\*(C`numbered.txt\*(C'\fR. This can start to look a little
429 tricky, because that same symbol would have meant something
430 entirely different had it showed it in the second argument to \f(CW\*(C`open\*(C'\fR!
431 But here in the third argument, it\*(Aqs simply part of the shell command that
432 Perl will open the pipe into, and Perl itself doesn\*(Aqt invest any special
433 meaning to it.
434 .SS "Expressing the command as a list"
435 .IX Subsection "Expressing the command as a list"
436 For opening pipes, Perl offers the option to call \f(CW\*(C`open\*(C'\fR with a list
437 comprising the desired command and all its own arguments as separate
438 elements, rather than combining them into a single string as in the
439 examples above. For instance, we could have phrased the \f(CW\*(C`open\*(C'\fR call in
440 the first example like this:
441 .PP
442 .Vb 2
443 \& open(my $sort_fh, \*(Aq\-|\*(Aq, \*(Aqsort\*(Aq, \*(Aq\-u\*(Aq, glob(\*(Aqunsorted/*.txt\*(Aq))
444 \& or die "Couldn\*(Aqt open a pipe into sort: $!";
445 .Ve
446 .PP
447 When you call \f(CW\*(C`open\*(C'\fR this way, Perl invokes the given command directly,
448 bypassing the shell. As such, the shell won\*(Aqt try to interpret any
449 special characters within the command\*(Aqs argument list, which might
450 otherwise have unwanted effects. This can make for safer, less
451 error\-prone \f(CW\*(C`open\*(C'\fR calls, useful in cases such as passing in variables
452 as arguments, or even just referring to filenames with spaces in them.
453 .PP
454 However, when you \fIdo\fR want to pass a meaningful metacharacter to the
455 shell, such with the \f(CW"*"\fR inside that final \f(CW\*(C`unsorted/*.txt\*(C'\fR argument
456 here, you can\*(Aqt use this alternate syntax. In this case, we have worked
457 around it via Perl\*(Aqs handy \f(CW\*(C`glob\*(C'\fR built\-in function, which evaluates
458 its argument into a list of filenames — and we can safely pass that
459 resulting list right into \f(CW\*(C`open\*(C'\fR, as shown above.
460 .PP
461 Note also that representing piped\-command arguments in list form like
462 this doesn\*(Aqt work on every platform. It will work on any Unix\-based OS
463 that provides a real \f(CW\*(C`fork\*(C'\fR function (e.g. macOS or Linux), as well as
464 on Windows when running Perl 5.22 or later.
465 .SH "SEE ALSO"
466 .IX Header "SEE ALSO"
467 The full documentation for \f(CW\*(C`open\*(C'\fR
468 provides a thorough reference to this function, beyond the best\-practice
469 basics covered here.
470 .SH "AUTHOR and COPYRIGHT"
471 .IX Header "AUTHOR and COPYRIGHT"
472 Copyright 2013 Tom Christiansen; now maintained by Perl5 Porters
473 .PP
474 This documentation is free; you can redistribute it and/or modify it under
475 the same terms as Perl itself.