This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
additional tests for package block syntax
[perl5.git] / pod / perlopentut.pod
1 =head1 NAME
2
3 perlopentut - tutorial on opening things in Perl
4
5 =head1 DESCRIPTION
6
7 Perl has two simple, built-in ways to open files: the shell way for
8 convenience, and the C way for precision.  The shell way also has 2- and
9 3-argument forms, which have different semantics for handling the filename.
10 The choice is yours.
11
12 =head1 Open E<agrave> la shell
13
14 Perl's C<open> function was designed to mimic the way command-line
15 redirection in the shell works.  Here are some basic examples
16 from the shell:
17
18     $ myprogram file1 file2 file3
19     $ myprogram    <  inputfile
20     $ myprogram    >  outputfile
21     $ myprogram    >> outputfile
22     $ myprogram    |  otherprogram 
23     $ otherprogram |  myprogram
24
25 And here are some more advanced examples:
26
27     $ otherprogram      | myprogram f1 - f2
28     $ otherprogram 2>&1 | myprogram -
29     $ myprogram     <&3
30     $ myprogram     >&4
31
32 Programmers accustomed to constructs like those above can take comfort
33 in learning that Perl directly supports these familiar constructs using
34 virtually the same syntax as the shell.
35
36 =head2 Simple Opens
37
38 The C<open> function takes two arguments: the first is a filehandle,
39 and the second is a single string comprising both what to open and how
40 to open it.  C<open> returns true when it works, and when it fails,
41 returns a false value and sets the special variable C<$!> to reflect
42 the system error.  If the filehandle was previously opened, it will
43 be implicitly closed first.
44
45 For example:
46
47     open(INFO,      "datafile") || die("can't open datafile: $!");
48     open(INFO,   "<  datafile") || die("can't open datafile: $!");
49     open(RESULTS,">  runstats") || die("can't open runstats: $!");
50     open(LOG,    ">> logfile ") || die("can't open logfile:  $!");
51
52 If you prefer the low-punctuation version, you could write that this way:
53
54     open INFO,   "<  datafile"  or die "can't open datafile: $!";
55     open RESULTS,">  runstats"  or die "can't open runstats: $!";
56     open LOG,    ">> logfile "  or die "can't open logfile:  $!";
57
58 A few things to notice.  First, the leading less-than is optional.
59 If omitted, Perl assumes that you want to open the file for reading.
60
61 Note also that the first example uses the C<||> logical operator, and the
62 second uses C<or>, which has lower precedence.  Using C<||> in the latter
63 examples would effectively mean
64
65     open INFO, ( "<  datafile"  || die "can't open datafile: $!" );
66
67 which is definitely not what you want.
68
69 The other important thing to notice is that, just as in the shell,
70 any whitespace before or after the filename is ignored.  This is good,
71 because you wouldn't want these to do different things:
72
73     open INFO,   "<datafile"   
74     open INFO,   "< datafile" 
75     open INFO,   "<  datafile"
76
77 Ignoring surrounding whitespace also helps for when you read a filename
78 in from a different file, and forget to trim it before opening:
79
80     $filename = <INFO>;         # oops, \n still there
81     open(EXTRA, "< $filename") || die "can't open $filename: $!";
82
83 This is not a bug, but a feature.  Because C<open> mimics the shell in
84 its style of using redirection arrows to specify how to open the file, it
85 also does so with respect to extra whitespace around the filename itself
86 as well.  For accessing files with naughty names, see 
87 L<"Dispelling the Dweomer">.
88
89 There is also a 3-argument version of C<open>, which lets you put the
90 special redirection characters into their own argument:
91
92     open( INFO, ">", $datafile ) || die "Can't create $datafile: $!";
93
94 In this case, the filename to open is the actual string in C<$datafile>,
95 so you don't have to worry about C<$datafile> containing characters
96 that might influence the open mode, or whitespace at the beginning of
97 the filename that would be absorbed in the 2-argument version.  Also,
98 any reduction of unnecessary string interpolation is a good thing.
99
100 =head2 Indirect Filehandles
101
102 C<open>'s first argument can be a reference to a filehandle.  As of
103 perl 5.6.0, if the argument is uninitialized, Perl will automatically
104 create a filehandle and put a reference to it in the first argument,
105 like so:
106
107     open( my $in, $infile )   or die "Couldn't read $infile: $!";
108     while ( <$in> ) {
109         # do something with $_
110     }
111     close $in;
112
113 Indirect filehandles make namespace management easier.  Since filehandles
114 are global to the current package, two subroutines trying to open
115 C<INFILE> will clash.  With two functions opening indirect filehandles
116 like C<my $infile>, there's no clash and no need to worry about future
117 conflicts.
118
119 Another convenient behavior is that an indirect filehandle automatically
120 closes when it goes out of scope or when you undefine it:
121
122     sub firstline {
123         open( my $in, shift ) && return scalar <$in>;
124         # no close() required
125     }
126
127 =head2 Pipe Opens
128
129 In C, when you want to open a file using the standard I/O library,
130 you use the C<fopen> function, but when opening a pipe, you use the
131 C<popen> function.  But in the shell, you just use a different redirection
132 character.  That's also the case for Perl.  The C<open> call 
133 remains the same--just its argument differs.  
134
135 If the leading character is a pipe symbol, C<open> starts up a new
136 command and opens a write-only filehandle leading into that command.
137 This lets you write into that handle and have what you write show up on
138 that command's standard input.  For example:
139
140     open(PRINTER, "| lpr -Plp1")    || die "can't run lpr: $!";
141     print PRINTER "stuff\n";
142     close(PRINTER)                  || die "can't close lpr: $!";
143
144 If the trailing character is a pipe, you start up a new command and open a
145 read-only filehandle leading out of that command.  This lets whatever that
146 command writes to its standard output show up on your handle for reading.
147 For example:
148
149     open(NET, "netstat -i -n |")    || die "can't fork netstat: $!";
150     while (<NET>) { }               # do something with input
151     close(NET)                      || die "can't close netstat: $!";
152
153 What happens if you try to open a pipe to or from a non-existent
154 command?  If possible, Perl will detect the failure and set C<$!> as
155 usual.  But if the command contains special shell characters, such as
156 C<E<gt>> or C<*>, called 'metacharacters', Perl does not execute the
157 command directly.  Instead, Perl runs the shell, which then tries to
158 run the command.  This means that it's the shell that gets the error
159 indication.  In such a case, the C<open> call will only indicate
160 failure if Perl can't even run the shell.  See L<perlfaq8/"How can I
161 capture STDERR from an external command?"> to see how to cope with
162 this.  There's also an explanation in L<perlipc>.
163
164 If you would like to open a bidirectional pipe, the IPC::Open2
165 library will handle this for you.  Check out 
166 L<perlipc/"Bidirectional Communication with Another Process">
167
168 perl-5.6.x introduced a version of piped open that executes a process
169 based on its command line arguments without relying on the shell. (Similar
170 to the C<system(@LIST)> notation.) This is safer and faster than executing
171 a single argument pipe-command, but does not allow special shell
172 constructs. (It is also not supported on Microsoft Windows, Mac OS Classic
173 or RISC OS.)
174
175 Here's an example of C<open '-|'>, which prints a random Unix
176 fortune cookie as uppercase:
177
178     my $collection = shift(@ARGV);
179     open my $fortune, '-|', 'fortune', $collection
180         or die "Could not find fortune - $!";
181     while (<$fortune>)
182     {
183         print uc($_);
184     }
185     close($fortune);
186
187 And this C<open '|-'> pipes into lpr:
188
189     open my $printer, '|-', 'lpr', '-Plp1'
190         or die "can't run lpr: $!";
191     print {$printer} "stuff\n";
192     close($printer)
193         or die "can't close lpr: $!";
194
195 =head2 The Minus File
196
197 Again following the lead of the standard shell utilities, Perl's
198 C<open> function treats a file whose name is a single minus, "-", in a
199 special way.  If you open minus for reading, it really means to access
200 the standard input.  If you open minus for writing, it really means to
201 access the standard output.
202
203 If minus can be used as the default input or default output, what happens
204 if you open a pipe into or out of minus?  What's the default command it
205 would run?  The same script as you're currently running!  This is actually
206 a stealth C<fork> hidden inside an C<open> call.  See 
207 L<perlipc/"Safe Pipe Opens"> for details.
208
209 =head2 Mixing Reads and Writes
210
211 It is possible to specify both read and write access.  All you do is
212 add a "+" symbol in front of the redirection.  But as in the shell,
213 using a less-than on a file never creates a new file; it only opens an
214 existing one.  On the other hand, using a greater-than always clobbers
215 (truncates to zero length) an existing file, or creates a brand-new one
216 if there isn't an old one.  Adding a "+" for read-write doesn't affect
217 whether it only works on existing files or always clobbers existing ones.
218
219     open(WTMP, "+< /usr/adm/wtmp") 
220         || die "can't open /usr/adm/wtmp: $!";
221
222     open(SCREEN, "+> lkscreen")
223         || die "can't open lkscreen: $!";
224
225     open(LOGFILE, "+>> /var/log/applog")
226         || die "can't open /var/log/applog: $!";
227
228 The first one won't create a new file, and the second one will always
229 clobber an old one.  The third one will create a new file if necessary
230 and not clobber an old one, and it will allow you to read at any point
231 in the file, but all writes will always go to the end.  In short,
232 the first case is substantially more common than the second and third
233 cases, which are almost always wrong.  (If you know C, the plus in
234 Perl's C<open> is historically derived from the one in C's fopen(3S),
235 which it ultimately calls.)
236
237 In fact, when it comes to updating a file, unless you're working on
238 a binary file as in the WTMP case above, you probably don't want to
239 use this approach for updating.  Instead, Perl's B<-i> flag comes to
240 the rescue.  The following command takes all the C, C++, or yacc source
241 or header files and changes all their foo's to bar's, leaving
242 the old version in the original filename with a ".orig" tacked
243 on the end:
244
245     $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]
246
247 This is a short cut for some renaming games that are really
248 the best way to update textfiles.  See the second question in 
249 L<perlfaq5> for more details.
250
251 =head2 Filters 
252
253 One of the most common uses for C<open> is one you never
254 even notice.  When you process the ARGV filehandle using
255 C<< <ARGV> >>, Perl actually does an implicit open 
256 on each file in @ARGV.  Thus a program called like this:
257
258     $ myprogram file1 file2 file3
259
260 can have all its files opened and processed one at a time
261 using a construct no more complex than:
262
263     while (<>) {
264         # do something with $_
265     } 
266
267 If @ARGV is empty when the loop first begins, Perl pretends you've opened
268 up minus, that is, the standard input.  In fact, $ARGV, the currently
269 open file during C<< <ARGV> >> processing, is even set to "-"
270 in these circumstances.
271
272 You are welcome to pre-process your @ARGV before starting the loop to
273 make sure it's to your liking.  One reason to do this might be to remove
274 command options beginning with a minus.  While you can always roll the
275 simple ones by hand, the Getopts modules are good for this:
276
277     use Getopt::Std;
278
279     # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o
280     getopts("vDo:");            
281
282     # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
283     getopts("vDo:", \%args);    
284
285 Or the standard Getopt::Long module to permit named arguments:
286
287     use Getopt::Long;
288     GetOptions( "verbose"  => \$verbose,        # --verbose
289                 "Debug"    => \$debug,          # --Debug
290                 "output=s" => \$output );       
291             # --output=somestring or --output somestring
292
293 Another reason for preprocessing arguments is to make an empty
294 argument list default to all files:
295
296     @ARGV = glob("*") unless @ARGV;
297
298 You could even filter out all but plain, text files.  This is a bit
299 silent, of course, and you might prefer to mention them on the way.
300
301     @ARGV = grep { -f && -T } @ARGV;
302
303 If you're using the B<-n> or B<-p> command-line options, you
304 should put changes to @ARGV in a C<BEGIN{}> block.
305
306 Remember that a normal C<open> has special properties, in that it might
307 call fopen(3S) or it might called popen(3S), depending on what its
308 argument looks like; that's why it's sometimes called "magic open".
309 Here's an example:
310
311     $pwdinfo = `domainname` =~ /^(\(none\))?$/
312                     ? '< /etc/passwd'
313                     : 'ypcat passwd |';
314
315     open(PWD, $pwdinfo)                 
316                 or die "can't open $pwdinfo: $!";
317
318 This sort of thing also comes into play in filter processing.  Because
319 C<< <ARGV> >> processing employs the normal, shell-style Perl C<open>,
320 it respects all the special things we've already seen:
321
322     $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
323
324 That program will read from the file F<f1>, the process F<cmd1>, standard
325 input (F<tmpfile> in this case), the F<f2> file, the F<cmd2> command,
326 and finally the F<f3> file.
327
328 Yes, this also means that if you have files named "-" (and so on) in
329 your directory, they won't be processed as literal files by C<open>.
330 You'll need to pass them as "./-", much as you would for the I<rm> program,
331 or you could use C<sysopen> as described below.
332
333 One of the more interesting applications is to change files of a certain
334 name into pipes.  For example, to autoprocess gzipped or compressed
335 files by decompressing them with I<gzip>:
336
337     @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc $_ |" : $_  } @ARGV;
338
339 Or, if you have the I<GET> program installed from LWP,
340 you can fetch URLs before processing them:
341
342     @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;
343
344 It's not for nothing that this is called magic C<< <ARGV> >>.
345 Pretty nifty, eh?
346
347 =head1 Open E<agrave> la C
348
349 If you want the convenience of the shell, then Perl's C<open> is
350 definitely the way to go.  On the other hand, if you want finer precision
351 than C's simplistic fopen(3S) provides you should look to Perl's
352 C<sysopen>, which is a direct hook into the open(2) system call.
353 That does mean it's a bit more involved, but that's the price of 
354 precision.
355
356 C<sysopen> takes 3 (or 4) arguments.
357
358     sysopen HANDLE, PATH, FLAGS, [MASK]
359
360 The HANDLE argument is a filehandle just as with C<open>.  The PATH is
361 a literal path, one that doesn't pay attention to any greater-thans or
362 less-thans or pipes or minuses, nor ignore whitespace.  If it's there,
363 it's part of the path.  The FLAGS argument contains one or more values
364 derived from the Fcntl module that have been or'd together using the
365 bitwise "|" operator.  The final argument, the MASK, is optional; if
366 present, it is combined with the user's current umask for the creation
367 mode of the file.  You should usually omit this.
368
369 Although the traditional values of read-only, write-only, and read-write
370 are 0, 1, and 2 respectively, this is known not to hold true on some
371 systems.  Instead, it's best to load in the appropriate constants first
372 from the Fcntl module, which supplies the following standard flags:
373
374     O_RDONLY            Read only
375     O_WRONLY            Write only
376     O_RDWR              Read and write
377     O_CREAT             Create the file if it doesn't exist
378     O_EXCL              Fail if the file already exists
379     O_APPEND            Append to the file
380     O_TRUNC             Truncate the file
381     O_NONBLOCK          Non-blocking access
382
383 Less common flags that are sometimes available on some operating
384 systems include C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>,
385 C<O_DEFER>, C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>,
386 C<O_NOCTTY>, C<O_NDELAY> and C<O_LARGEFILE>.  Consult your open(2)
387 manpage or its local equivalent for details.  (Note: starting from
388 Perl release 5.6 the C<O_LARGEFILE> flag, if available, is automatically
389 added to the sysopen() flags because large files are the default.)
390
391 Here's how to use C<sysopen> to emulate the simple C<open> calls we had
392 before.  We'll omit the C<|| die $!> checks for clarity, but make sure
393 you always check the return values in real code.  These aren't quite
394 the same, since C<open> will trim leading and trailing whitespace,
395 but you'll get the idea.
396
397 To open a file for reading:
398
399     open(FH, "< $path");
400     sysopen(FH, $path, O_RDONLY);
401
402 To open a file for writing, creating a new file if needed or else truncating
403 an old file:
404
405     open(FH, "> $path");
406     sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);
407
408 To open a file for appending, creating one if necessary:
409
410     open(FH, ">> $path");
411     sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);
412
413 To open a file for update, where the file must already exist:
414
415     open(FH, "+< $path");
416     sysopen(FH, $path, O_RDWR);
417
418 And here are things you can do with C<sysopen> that you cannot do with
419 a regular C<open>.  As you'll see, it's just a matter of controlling the
420 flags in the third argument.
421
422 To open a file for writing, creating a new file which must not previously
423 exist:
424
425     sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);
426
427 To open a file for appending, where that file must already exist:
428
429     sysopen(FH, $path, O_WRONLY | O_APPEND);
430
431 To open a file for update, creating a new file if necessary:
432
433     sysopen(FH, $path, O_RDWR | O_CREAT);
434
435 To open a file for update, where that file must not already exist:
436
437     sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);
438
439 To open a file without blocking, creating one if necessary:
440
441     sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);
442
443 =head2 Permissions E<agrave> la mode
444
445 If you omit the MASK argument to C<sysopen>, Perl uses the octal value
446 0666.  The normal MASK to use for executables and directories should
447 be 0777, and for anything else, 0666.
448
449 Why so permissive?  Well, it isn't really.  The MASK will be modified
450 by your process's current C<umask>.  A umask is a number representing
451 I<disabled> permissions bits; that is, bits that will not be turned on
452 in the created file's permissions field.
453
454 For example, if your C<umask> were 027, then the 020 part would
455 disable the group from writing, and the 007 part would disable others
456 from reading, writing, or executing.  Under these conditions, passing
457 C<sysopen> 0666 would create a file with mode 0640, since C<0666 & ~027>
458 is 0640.
459
460 You should seldom use the MASK argument to C<sysopen()>.  That takes
461 away the user's freedom to choose what permission new files will have.
462 Denying choice is almost always a bad thing.  One exception would be for
463 cases where sensitive or private data is being stored, such as with mail
464 folders, cookie files, and internal temporary files.
465
466 =head1 Obscure Open Tricks
467
468 =head2 Re-Opening Files (dups)
469
470 Sometimes you already have a filehandle open, and want to make another
471 handle that's a duplicate of the first one.  In the shell, we place an
472 ampersand in front of a file descriptor number when doing redirections.
473 For example, C<< 2>&1 >> makes descriptor 2 (that's STDERR in Perl)
474 be redirected into descriptor 1 (which is usually Perl's STDOUT).
475 The same is essentially true in Perl: a filename that begins with an
476 ampersand is treated instead as a file descriptor if a number, or as a
477 filehandle if a string.
478
479     open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
480     open(MHCONTEXT, "<&4")     || die "couldn't dup fd4: $!";
481
482 That means that if a function is expecting a filename, but you don't
483 want to give it a filename because you already have the file open, you
484 can just pass the filehandle with a leading ampersand.  It's best to
485 use a fully qualified handle though, just in case the function happens
486 to be in a different package:
487
488     somefunction("&main::LOGFILE");
489
490 This way if somefunction() is planning on opening its argument, it can
491 just use the already opened handle.  This differs from passing a handle,
492 because with a handle, you don't open the file.  Here you have something
493 you can pass to open.
494
495 If you have one of those tricky, newfangled I/O objects that the C++
496 folks are raving about, then this doesn't work because those aren't a
497 proper filehandle in the native Perl sense.  You'll have to use fileno()
498 to pull out the proper descriptor number, assuming you can:
499
500     use IO::Socket;
501     $handle = IO::Socket::INET->new("www.perl.com:80");
502     $fd = $handle->fileno;
503     somefunction("&$fd");  # not an indirect function call
504
505 It can be easier (and certainly will be faster) just to use real
506 filehandles though:
507
508     use IO::Socket;
509     local *REMOTE = IO::Socket::INET->new("www.perl.com:80");
510     die "can't connect" unless defined(fileno(REMOTE));
511     somefunction("&main::REMOTE");
512
513 If the filehandle or descriptor number is preceded not just with a simple
514 "&" but rather with a "&=" combination, then Perl will not create a
515 completely new descriptor opened to the same place using the dup(2)
516 system call.  Instead, it will just make something of an alias to the
517 existing one using the fdopen(3S) library call.  This is slightly more
518 parsimonious of systems resources, although this is less a concern
519 these days.  Here's an example of that:
520
521     $fd = $ENV{"MHCONTEXTFD"};
522     open(MHCONTEXT, "<&=$fd")   or die "couldn't fdopen $fd: $!";
523
524 If you're using magic C<< <ARGV> >>, you could even pass in as a
525 command line argument in @ARGV something like C<"<&=$MHCONTEXTFD">,
526 but we've never seen anyone actually do this.
527
528 =head2 Dispelling the Dweomer
529
530 Perl is more of a DWIMmer language than something like Java--where DWIM
531 is an acronym for "do what I mean".  But this principle sometimes leads
532 to more hidden magic than one knows what to do with.  In this way, Perl
533 is also filled with I<dweomer>, an obscure word meaning an enchantment.
534 Sometimes, Perl's DWIMmer is just too much like dweomer for comfort.
535
536 If magic C<open> is a bit too magical for you, you don't have to turn
537 to C<sysopen>.  To open a file with arbitrary weird characters in
538 it, it's necessary to protect any leading and trailing whitespace.
539 Leading whitespace is protected by inserting a C<"./"> in front of a
540 filename that starts with whitespace.  Trailing whitespace is protected
541 by appending an ASCII NUL byte (C<"\0">) at the end of the string.
542
543     $file =~ s#^(\s)#./$1#;
544     open(FH, "< $file\0")   || die "can't open $file: $!";
545
546 This assumes, of course, that your system considers dot the current
547 working directory, slash the directory separator, and disallows ASCII
548 NULs within a valid filename.  Most systems follow these conventions,
549 including all POSIX systems as well as proprietary Microsoft systems.
550 The only vaguely popular system that doesn't work this way is the
551 "Classic" Macintosh system, which uses a colon where the rest of us
552 use a slash.  Maybe C<sysopen> isn't such a bad idea after all.
553
554 If you want to use C<< <ARGV> >> processing in a totally boring
555 and non-magical way, you could do this first:
556
557     #   "Sam sat on the ground and put his head in his hands.  
558     #   'I wish I had never come here, and I don't want to see 
559     #   no more magic,' he said, and fell silent."
560     for (@ARGV) { 
561         s#^([^./])#./$1#;
562         $_ .= "\0";
563     } 
564     while (<>) {  
565         # now process $_
566     } 
567
568 But be warned that users will not appreciate being unable to use "-"
569 to mean standard input, per the standard convention.
570
571 =head2 Paths as Opens
572
573 You've probably noticed how Perl's C<warn> and C<die> functions can
574 produce messages like:
575
576     Some warning at scriptname line 29, <FH> line 7.
577
578 That's because you opened a filehandle FH, and had read in seven records
579 from it.  But what was the name of the file, rather than the handle?
580
581 If you aren't running with C<strict refs>, or if you've turned them off
582 temporarily, then all you have to do is this:
583
584     open($path, "< $path") || die "can't open $path: $!";
585     while (<$path>) {
586         # whatever
587     } 
588
589 Since you're using the pathname of the file as its handle,
590 you'll get warnings more like
591
592     Some warning at scriptname line 29, </etc/motd> line 7.
593
594 =head2 Single Argument Open
595
596 Remember how we said that Perl's open took two arguments?  That was a
597 passive prevarication.  You see, it can also take just one argument.
598 If and only if the variable is a global variable, not a lexical, you
599 can pass C<open> just one argument, the filehandle, and it will 
600 get the path from the global scalar variable of the same name.
601
602     $FILE = "/etc/motd";
603     open FILE or die "can't open $FILE: $!";
604     while (<FILE>) {
605         # whatever
606     } 
607
608 Why is this here?  Someone has to cater to the hysterical porpoises.
609 It's something that's been in Perl since the very beginning, if not
610 before.
611
612 =head2 Playing with STDIN and STDOUT
613
614 One clever move with STDOUT is to explicitly close it when you're done
615 with the program.
616
617     END { close(STDOUT) || die "can't close stdout: $!" }
618
619 If you don't do this, and your program fills up the disk partition due
620 to a command line redirection, it won't report the error exit with a
621 failure status.
622
623 You don't have to accept the STDIN and STDOUT you were given.  You are
624 welcome to reopen them if you'd like.
625
626     open(STDIN, "< datafile")
627         || die "can't open datafile: $!";
628
629     open(STDOUT, "> output")
630         || die "can't open output: $!";
631
632 And then these can be accessed directly or passed on to subprocesses.
633 This makes it look as though the program were initially invoked
634 with those redirections from the command line.
635
636 It's probably more interesting to connect these to pipes.  For example:
637
638     $pager = $ENV{PAGER} || "(less || more)";
639     open(STDOUT, "| $pager")
640         || die "can't fork a pager: $!";
641
642 This makes it appear as though your program were called with its stdout
643 already piped into your pager.  You can also use this kind of thing
644 in conjunction with an implicit fork to yourself.  You might do this
645 if you would rather handle the post processing in your own program,
646 just in a different process:
647
648     head(100);
649     while (<>) {
650         print;
651     } 
652
653     sub head {
654         my $lines = shift || 20;
655         return if $pid = open(STDOUT, "|-");       # return if parent
656         die "cannot fork: $!" unless defined $pid;
657         while (<STDIN>) {
658             last if --$lines < 0;
659             print;
660         } 
661         exit;
662     } 
663
664 This technique can be applied to repeatedly push as many filters on your
665 output stream as you wish.
666
667 =head1 Other I/O Issues
668
669 These topics aren't really arguments related to C<open> or C<sysopen>,
670 but they do affect what you do with your open files.
671
672 =head2 Opening Non-File Files
673
674 When is a file not a file?  Well, you could say when it exists but
675 isn't a plain file.   We'll check whether it's a symbolic link first,
676 just in case.
677
678     if (-l $file || ! -f _) {
679         print "$file is not a plain file\n";
680     } 
681
682 What other kinds of files are there than, well, files?  Directories,
683 symbolic links, named pipes, Unix-domain sockets, and block and character
684 devices.  Those are all files, too--just not I<plain> files.  This isn't
685 the same issue as being a text file. Not all text files are plain files.
686 Not all plain files are text files.  That's why there are separate C<-f>
687 and C<-T> file tests.
688
689 To open a directory, you should use the C<opendir> function, then
690 process it with C<readdir>, carefully restoring the directory 
691 name if necessary:
692
693     opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
694     while (defined($file = readdir(DIR))) {
695         # do something with "$dirname/$file"
696     }
697     closedir(DIR);
698
699 If you want to process directories recursively, it's better to use the
700 File::Find module.  For example, this prints out all files recursively
701 and adds a slash to their names if the file is a directory.
702
703     @ARGV = qw(.) unless @ARGV;
704     use File::Find;
705     find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
706
707 This finds all bogus symbolic links beneath a particular directory:
708
709     find sub { print "$File::Find::name\n" if -l && !-e }, $dir;
710
711 As you see, with symbolic links, you can just pretend that it is
712 what it points to.  Or, if you want to know I<what> it points to, then
713 C<readlink> is called for:
714
715     if (-l $file) {
716         if (defined($whither = readlink($file))) {
717             print "$file points to $whither\n";
718         } else {
719             print "$file points nowhere: $!\n";
720         } 
721     } 
722
723 =head2 Opening Named Pipes
724
725 Named pipes are a different matter.  You pretend they're regular files,
726 but their opens will normally block until there is both a reader and
727 a writer.  You can read more about them in L<perlipc/"Named Pipes">.
728 Unix-domain sockets are rather different beasts as well; they're
729 described in L<perlipc/"Unix-Domain TCP Clients and Servers">.
730
731 When it comes to opening devices, it can be easy and it can be tricky.
732 We'll assume that if you're opening up a block device, you know what
733 you're doing.  The character devices are more interesting.  These are
734 typically used for modems, mice, and some kinds of printers.  This is
735 described in L<perlfaq8/"How do I read and write the serial port?">
736 It's often enough to open them carefully:
737
738     sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
739                 # (O_NOCTTY no longer needed on POSIX systems)
740         or die "can't open /dev/ttyS1: $!";
741     open(TTYOUT, "+>&TTYIN")
742         or die "can't dup TTYIN: $!";
743
744     $ofh = select(TTYOUT); $| = 1; select($ofh);
745
746     print TTYOUT "+++at\015";
747     $answer = <TTYIN>;
748
749 With descriptors that you haven't opened using C<sysopen>, such as
750 sockets, you can set them to be non-blocking using C<fcntl>:
751
752     use Fcntl;
753     my $old_flags = fcntl($handle, F_GETFL, 0) 
754         or die "can't get flags: $!";
755     fcntl($handle, F_SETFL, $old_flags | O_NONBLOCK) 
756         or die "can't set non blocking: $!";
757
758 Rather than losing yourself in a morass of twisting, turning C<ioctl>s,
759 all dissimilar, if you're going to manipulate ttys, it's best to
760 make calls out to the stty(1) program if you have it, or else use the
761 portable POSIX interface.  To figure this all out, you'll need to read the
762 termios(3) manpage, which describes the POSIX interface to tty devices,
763 and then L<POSIX>, which describes Perl's interface to POSIX.  There are
764 also some high-level modules on CPAN that can help you with these games.
765 Check out Term::ReadKey and Term::ReadLine.
766
767 =head2 Opening Sockets
768
769 What else can you open?  To open a connection using sockets, you won't use
770 one of Perl's two open functions.  See 
771 L<perlipc/"Sockets: Client/Server Communication"> for that.  Here's an 
772 example.  Once you have it, you can use FH as a bidirectional filehandle.
773
774     use IO::Socket;
775     local *FH = IO::Socket::INET->new("www.perl.com:80");
776
777 For opening up a URL, the LWP modules from CPAN are just what
778 the doctor ordered.  There's no filehandle interface, but
779 it's still easy to get the contents of a document:
780
781     use LWP::Simple;
782     $doc = get('http://www.cpan.org/');
783
784 =head2 Binary Files
785
786 On certain legacy systems with what could charitably be called terminally
787 convoluted (some would say broken) I/O models, a file isn't a file--at
788 least, not with respect to the C standard I/O library.  On these old
789 systems whose libraries (but not kernels) distinguish between text and
790 binary streams, to get files to behave properly you'll have to bend over
791 backwards to avoid nasty problems.  On such infelicitous systems, sockets
792 and pipes are already opened in binary mode, and there is currently no
793 way to turn that off.  With files, you have more options.
794
795 Another option is to use the C<binmode> function on the appropriate
796 handles before doing regular I/O on them:
797
798     binmode(STDIN);
799     binmode(STDOUT);
800     while (<STDIN>) { print } 
801
802 Passing C<sysopen> a non-standard flag option will also open the file in
803 binary mode on those systems that support it.  This is the equivalent of
804 opening the file normally, then calling C<binmode> on the handle.
805
806     sysopen(BINDAT, "records.data", O_RDWR | O_BINARY)
807         || die "can't open records.data: $!";
808
809 Now you can use C<read> and C<print> on that handle without worrying
810 about the non-standard system I/O library breaking your data.  It's not
811 a pretty picture, but then, legacy systems seldom are.  CP/M will be
812 with us until the end of days, and after.
813
814 On systems with exotic I/O systems, it turns out that, astonishingly
815 enough, even unbuffered I/O using C<sysread> and C<syswrite> might do
816 sneaky data mutilation behind your back.
817
818     while (sysread(WHENCE, $buf, 1024)) {
819         syswrite(WHITHER, $buf, length($buf));
820     } 
821
822 Depending on the vicissitudes of your runtime system, even these calls
823 may need C<binmode> or C<O_BINARY> first.  Systems known to be free of
824 such difficulties include Unix, the Mac OS, Plan 9, and Inferno.
825
826 =head2 File Locking
827
828 In a multitasking environment, you may need to be careful not to collide
829 with other processes who want to do I/O on the same files as you
830 are working on.  You'll often need shared or exclusive locks
831 on files for reading and writing respectively.  You might just
832 pretend that only exclusive locks exist.
833
834 Never use the existence of a file C<-e $file> as a locking indication,
835 because there is a race condition between the test for the existence of
836 the file and its creation.  It's possible for another process to create
837 a file in the slice of time between your existence check and your attempt
838 to create the file.  Atomicity is critical.
839
840 Perl's most portable locking interface is via the C<flock> function,
841 whose simplicity is emulated on systems that don't directly support it
842 such as SysV or Windows.  The underlying semantics may affect how
843 it all works, so you should learn how C<flock> is implemented on your
844 system's port of Perl.
845
846 File locking I<does not> lock out another process that would like to
847 do I/O.  A file lock only locks out others trying to get a lock, not
848 processes trying to do I/O.  Because locks are advisory, if one process
849 uses locking and another doesn't, all bets are off.
850
851 By default, the C<flock> call will block until a lock is granted.
852 A request for a shared lock will be granted as soon as there is no
853 exclusive locker.  A request for an exclusive lock will be granted as
854 soon as there is no locker of any kind.  Locks are on file descriptors,
855 not file names.  You can't lock a file until you open it, and you can't
856 hold on to a lock once the file has been closed.
857
858 Here's how to get a blocking shared lock on a file, typically used
859 for reading:
860
861     use 5.004;
862     use Fcntl qw(:DEFAULT :flock);
863     open(FH, "< filename")  or die "can't open filename: $!";
864     flock(FH, LOCK_SH)      or die "can't lock filename: $!";
865     # now read from FH
866
867 You can get a non-blocking lock by using C<LOCK_NB>.
868
869     flock(FH, LOCK_SH | LOCK_NB)
870         or die "can't lock filename: $!";
871
872 This can be useful for producing more user-friendly behaviour by warning
873 if you're going to be blocking:
874
875     use 5.004;
876     use Fcntl qw(:DEFAULT :flock);
877     open(FH, "< filename")  or die "can't open filename: $!";
878     unless (flock(FH, LOCK_SH | LOCK_NB)) {
879         $| = 1;
880         print "Waiting for lock...";
881         flock(FH, LOCK_SH)  or die "can't lock filename: $!";
882         print "got it.\n"
883     } 
884     # now read from FH
885
886 To get an exclusive lock, typically used for writing, you have to be
887 careful.  We C<sysopen> the file so it can be locked before it gets
888 emptied.  You can get a nonblocking version using C<LOCK_EX | LOCK_NB>.
889
890     use 5.004;
891     use Fcntl qw(:DEFAULT :flock);
892     sysopen(FH, "filename", O_WRONLY | O_CREAT)
893         or die "can't open filename: $!";
894     flock(FH, LOCK_EX)
895         or die "can't lock filename: $!";
896     truncate(FH, 0)
897         or die "can't truncate filename: $!";
898     # now write to FH
899
900 Finally, due to the uncounted millions who cannot be dissuaded from
901 wasting cycles on useless vanity devices called hit counters, here's
902 how to increment a number in a file safely:
903
904     use Fcntl qw(:DEFAULT :flock);
905
906     sysopen(FH, "numfile", O_RDWR | O_CREAT)
907         or die "can't open numfile: $!";
908     # autoflush FH
909     $ofh = select(FH); $| = 1; select ($ofh);
910     flock(FH, LOCK_EX)
911         or die "can't write-lock numfile: $!";
912
913     $num = <FH> || 0;
914     seek(FH, 0, 0)
915         or die "can't rewind numfile : $!";
916     print FH $num+1, "\n"
917         or die "can't write numfile: $!";
918
919     truncate(FH, tell(FH))
920         or die "can't truncate numfile: $!";
921     close(FH)
922         or die "can't close numfile: $!";
923
924 =head2 IO Layers
925
926 In Perl 5.8.0 a new I/O framework called "PerlIO" was introduced.
927 This is a new "plumbing" for all the I/O happening in Perl; for the
928 most part everything will work just as it did, but PerlIO also brought
929 in some new features such as the ability to think of I/O as "layers".
930 One I/O layer may in addition to just moving the data also do
931 transformations on the data.  Such transformations may include
932 compression and decompression, encryption and decryption, and transforming
933 between various character encodings.
934
935 Full discussion about the features of PerlIO is out of scope for this
936 tutorial, but here is how to recognize the layers being used:
937
938 =over 4
939
940 =item *
941
942 The three-(or more)-argument form of C<open> is being used and the
943 second argument contains something else in addition to the usual
944 C<< '<' >>, C<< '>' >>, C<< '>>' >>, C<< '|' >> and their variants,
945 for example:
946
947     open(my $fh, "<:crlf", $fn);
948
949 =item *
950
951 The two-argument form of C<binmode> is being used, for example
952
953     binmode($fh, ":encoding(utf16)");
954
955 =back
956
957 For more detailed discussion about PerlIO see L<PerlIO>;
958 for more detailed discussion about Unicode and I/O see L<perluniintro>.
959
960 =head1 SEE ALSO 
961
962 The C<open> and C<sysopen> functions in perlfunc(1);
963 the system open(2), dup(2), fopen(3), and fdopen(3) manpages;
964 the POSIX documentation.
965
966 =head1 AUTHOR and COPYRIGHT
967
968 Copyright 1998 Tom Christiansen.  
969
970 This documentation is free; you can redistribute it and/or modify it
971 under the same terms as Perl itself.
972
973 Irrespective of its distribution, all code examples in these files are
974 hereby placed into the public domain.  You are permitted and
975 encouraged to use this code in your own programs for fun or for profit
976 as you see fit.  A simple comment in the code giving credit would be
977 courteous but is not required.
978
979 =head1 HISTORY
980
981 First release: Sat Jan  9 08:09:11 MST 1999