8c4aa2f0c9274937a93c55eacf9e2d662d28a9a7
[p5sagit/p5-mst-13.2.git] / pod / perlfaq5.pod
1 =head1 NAME
2
3 perlfaq5 - Files and Formats ($Revision: 1.9 $, $Date: 2002/02/11 19:30:21 $)
4
5 =head1 DESCRIPTION
6
7 This section deals with I/O and the "f" issues: filehandles, flushing,
8 formats, and footers.
9
10 =head2 How do I flush/unbuffer an output filehandle?  Why must I do this?
11
12 The C standard I/O library (stdio) normally buffers characters sent to
13 devices.  This is done for efficiency reasons so that there isn't a
14 system call for each byte.  Any time you use print() or write() in
15 Perl, you go though this buffering.  syswrite() circumvents stdio and
16 buffering.
17
18 In most stdio implementations, the type of output buffering and the size of
19 the buffer varies according to the type of device.  Disk files are block
20 buffered, often with a buffer size of more than 2k.  Pipes and sockets
21 are often buffered with a buffer size between 1/2 and 2k.  Serial devices
22 (e.g. modems, terminals) are normally line-buffered, and stdio sends
23 the entire line when it gets the newline.
24
25 Perl does not support truly unbuffered output (except insofar as you can
26 C<syswrite(OUT, $char, 1)>).  What it does instead support is "command
27 buffering", in which a physical write is performed after every output
28 command.  This isn't as hard on your system as unbuffering, but does
29 get the output where you want it when you want it.
30
31 If you expect characters to get to your device when you print them there,
32 you'll want to autoflush its handle.
33 Use select() and the C<$|> variable to control autoflushing
34 (see L<perlvar/$|> and L<perlfunc/select>):
35
36     $old_fh = select(OUTPUT_HANDLE);
37     $| = 1;
38     select($old_fh);
39
40 Or using the traditional idiom:
41
42     select((select(OUTPUT_HANDLE), $| = 1)[0]);
43
44 Or if don't mind slowly loading several thousand lines of module code
45 just because you're afraid of the C<$|> variable:
46
47     use FileHandle;
48     open(DEV, "+</dev/tty");      # ceci n'est pas une pipe
49     DEV->autoflush(1);
50
51 or the newer IO::* modules:
52
53     use IO::Handle;
54     open(DEV, ">/dev/printer");   # but is this?
55     DEV->autoflush(1);
56
57 or even this:
58
59     use IO::Socket;               # this one is kinda a pipe?
60     $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.com',
61                                   PeerPort => 'http(80)',
62                                   Proto    => 'tcp');
63     die "$!" unless $sock;
64
65     $sock->autoflush();
66     print $sock "GET / HTTP/1.0" . "\015\012" x 2;
67     $document = join('', <$sock>);
68     print "DOC IS: $document\n";
69
70 Note the bizarrely hard coded carriage return and newline in their octal
71 equivalents.  This is the ONLY way (currently) to assure a proper flush
72 on all platforms, including Macintosh.  That's the way things work in
73 network programming: you really should specify the exact bit pattern
74 on the network line terminator.  In practice, C<"\n\n"> often works,
75 but this is not portable.
76
77 See L<perlfaq9> for other examples of fetching URLs over the web.
78
79 =head2 How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file?
80
81 The short answer is to use the Tie::File module, which is included
82 in the standard distribution since Perl 5.8.0.
83
84 The long answer is that those are operations of a text editor.  Perl
85 is not a text editor.  Perl is a programming language.  You have to
86 decompose the problem into low-level calls to read, write, open,
87 close, and seek.
88
89 Although humans have an easy time thinking of a text file as being a
90 sequence of lines that operates much like a stack of playing cards--or
91 punch cards--computers usually see the text file as a sequence of bytes.
92 In general, there's no direct way for Perl to seek to a particular line
93 of a file, insert text into a file, or remove text from a file.
94
95 (There are exceptions in special circumstances.  You can add or remove
96 data at the very end of the file.  A sequence of bytes can be replaced
97 with another sequence of the same length.  The C<$DB_RECNO> array
98 bindings as documented in L<DB_File> also provide a direct way of
99 modifying a file.  Files where all lines are the same length are also
100 easy to alter.)
101
102 The general solution is to create a temporary copy of the text file with
103 the changes you want, then copy that over the original.  This assumes
104 no locking.
105
106     $old = $file;
107     $new = "$file.tmp.$$";
108     $bak = "$file.orig";
109
110     open(OLD, "< $old")         or die "can't open $old: $!";
111     open(NEW, "> $new")         or die "can't open $new: $!";
112
113     # Correct typos, preserving case
114     while (<OLD>) {
115         s/\b(p)earl\b/${1}erl/i;
116         (print NEW $_)          or die "can't write to $new: $!";
117     }
118
119     close(OLD)                  or die "can't close $old: $!";
120     close(NEW)                  or die "can't close $new: $!";
121
122     rename($old, $bak)          or die "can't rename $old to $bak: $!";
123     rename($new, $old)          or die "can't rename $new to $old: $!";
124
125 Perl can do this sort of thing for you automatically with the C<-i>
126 command-line switch or the closely-related C<$^I> variable (see
127 L<perlrun> for more details).  Note that
128 C<-i> may require a suffix on some non-Unix systems; see the
129 platform-specific documentation that came with your port.
130
131     # Renumber a series of tests from the command line
132     perl -pi -e 's/(^\s+test\s+)\d+/ $1 . ++$count /e' t/op/taint.t
133
134     # form a script
135     local($^I, @ARGV) = ('.orig', glob("*.c"));
136     while (<>) {
137         if ($. == 1) {
138             print "This line should appear at the top of each file\n";
139         }
140         s/\b(p)earl\b/${1}erl/i;        # Correct typos, preserving case
141         print;
142         close ARGV if eof;              # Reset $.
143     }
144
145 If you need to seek to an arbitrary line of a file that changes
146 infrequently, you could build up an index of byte positions of where
147 the line ends are in the file.  If the file is large, an index of
148 every tenth or hundredth line end would allow you to seek and read
149 fairly efficiently.  If the file is sorted, try the look.pl library
150 (part of the standard perl distribution).
151
152 In the unique case of deleting lines at the end of a file, you
153 can use tell() and truncate().  The following code snippet deletes
154 the last line of a file without making a copy or reading the
155 whole file into memory:
156
157         open (FH, "+< $file");
158         while ( <FH> ) { $addr = tell(FH) unless eof(FH) }
159         truncate(FH, $addr);
160
161 Error checking is left as an exercise for the reader.
162
163 =head2 How do I count the number of lines in a file?
164
165 One fairly efficient way is to count newlines in the file. The
166 following program uses a feature of tr///, as documented in L<perlop>.
167 If your text file doesn't end with a newline, then it's not really a
168 proper text file, so this may report one fewer line than you expect.
169
170     $lines = 0;
171     open(FILE, $filename) or die "Can't open `$filename': $!";
172     while (sysread FILE, $buffer, 4096) {
173         $lines += ($buffer =~ tr/\n//);
174     }
175     close FILE;
176
177 This assumes no funny games with newline translations.
178
179 =head2 How do I make a temporary file name?
180
181 Use the File::Temp module, see L<File::Temp> for more information.
182
183   use File::Temp qw/ tempfile tempdir /; 
184
185   $dir = tempdir( CLEANUP => 1 );
186   ($fh, $filename) = tempfile( DIR => $dir );
187
188   # or if you don't need to know the filename
189
190   $fh = tempfile( DIR => $dir );
191
192 The File::Temp has been a standard module since Perl 5.6.1.  If you
193 don't have a modern enough Perl installed, use the C<new_tmpfile>
194 class method from the IO::File module to get a filehandle opened for
195 reading and writing.  Use it if you don't need to know the file's name:
196
197     use IO::File;
198     $fh = IO::File->new_tmpfile()
199         or die "Unable to make new temporary file: $!";
200
201 If you're committed to creating a temporary file by hand, use the
202 process ID and/or the current time-value.  If you need to have many
203 temporary files in one process, use a counter:
204
205     BEGIN {
206         use Fcntl;
207         my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
208         my $base_name = sprintf("%s/%d-%d-0000", $temp_dir, $$, time());
209         sub temp_file {
210             local *FH;
211             my $count = 0;
212             until (defined(fileno(FH)) || $count++ > 100) {
213                 $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
214                 sysopen(FH, $base_name, O_WRONLY|O_EXCL|O_CREAT);
215             }
216             if (defined(fileno(FH))
217                 return (*FH, $base_name);
218             } else {
219                 return ();
220             }
221         }
222     }
223
224 =head2 How can I manipulate fixed-record-length files?
225
226 The most efficient way is using pack() and unpack().  This is faster than
227 using substr() when taking many, many strings.  It is slower for just a few.
228
229 Here is a sample chunk of code to break up and put back together again
230 some fixed-format input lines, in this case from the output of a normal,
231 Berkeley-style ps:
232
233     # sample input line:
234     #   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what
235     $PS_T = 'A6 A4 A7 A5 A*';
236     open(PS, "ps|");
237     print scalar <PS>; 
238     while (<PS>) {
239         ($pid, $tt, $stat, $time, $command) = unpack($PS_T, $_);
240         for $var (qw!pid tt stat time command!) {
241             print "$var: <$$var>\n";
242         }
243         print 'line=', pack($PS_T, $pid, $tt, $stat, $time, $command),
244                 "\n";
245     }
246
247 We've used C<$$var> in a way that forbidden by C<use strict 'refs'>.
248 That is, we've promoted a string to a scalar variable reference using
249 symbolic references.  This is okay in small programs, but doesn't scale
250 well.   It also only works on global variables, not lexicals.
251
252 =head2 How can I make a filehandle local to a subroutine?  How do I pass filehandles between subroutines?  How do I make an array of filehandles?
253
254 The fastest, simplest, and most direct way is to localize the typeglob
255 of the filehandle in question:
256
257     local *TmpHandle;
258
259 Typeglobs are fast (especially compared with the alternatives) and
260 reasonably easy to use, but they also have one subtle drawback.  If you
261 had, for example, a function named TmpHandle(), or a variable named
262 %TmpHandle, you just hid it from yourself.
263
264     sub findme {
265         local *HostFile;
266         open(HostFile, "</etc/hosts") or die "no /etc/hosts: $!";
267         local $_;               # <- VERY IMPORTANT
268         while (<HostFile>) {
269             print if /\b127\.(0\.0\.)?1\b/;
270         }
271         # *HostFile automatically closes/disappears here
272     }
273
274 Here's how to use typeglobs in a loop to open and store a bunch of
275 filehandles.  We'll use as values of the hash an ordered
276 pair to make it easy to sort the hash in insertion order.
277
278     @names = qw(motd termcap passwd hosts);
279     my $i = 0;
280     foreach $filename (@names) {
281         local *FH;
282         open(FH, "/etc/$filename") || die "$filename: $!";
283         $file{$filename} = [ $i++, *FH ];
284     }
285
286     # Using the filehandles in the array
287     foreach $name (sort { $file{$a}[0] <=> $file{$b}[0] } keys %file) {
288         my $fh = $file{$name}[1];
289         my $line = <$fh>;
290         print "$name $. $line";
291     }
292
293 For passing filehandles to functions, the easiest way is to 
294 preface them with a star, as in func(*STDIN).  
295 See L<perlfaq7/"Passing Filehandles"> for details.
296
297 If you want to create many anonymous handles, you should check out the
298 Symbol, FileHandle, or IO::Handle (etc.) modules.  Here's the equivalent
299 code with Symbol::gensym, which is reasonably light-weight:
300
301     foreach $filename (@names) {
302         use Symbol;
303         my $fh = gensym();
304         open($fh, "/etc/$filename") || die "open /etc/$filename: $!";
305         $file{$filename} = [ $i++, $fh ];
306     }
307
308 Here's using the semi-object-oriented FileHandle module, which certainly
309 isn't light-weight:
310
311     use FileHandle;
312
313     foreach $filename (@names) {
314         my $fh = FileHandle->new("/etc/$filename") or die "$filename: $!";
315         $file{$filename} = [ $i++, $fh ];
316     }
317
318 Please understand that whether the filehandle happens to be a (probably
319 localized) typeglob or an anonymous handle from one of the modules
320 in no way affects the bizarre rules for managing indirect handles.
321 See the next question.
322
323 =head2 How can I use a filehandle indirectly?
324
325 An indirect filehandle is using something other than a symbol
326 in a place that a filehandle is expected.  Here are ways
327 to get indirect filehandles:
328
329     $fh =   SOME_FH;       # bareword is strict-subs hostile
330     $fh =  "SOME_FH";      # strict-refs hostile; same package only
331     $fh =  *SOME_FH;       # typeglob
332     $fh = \*SOME_FH;       # ref to typeglob (bless-able)
333     $fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH typeglob
334
335 Or, you can use the C<new> method from the FileHandle or IO modules to
336 create an anonymous filehandle, store that in a scalar variable,
337 and use it as though it were a normal filehandle.
338
339     use FileHandle;
340     $fh = FileHandle->new();
341
342     use IO::Handle;                     # 5.004 or higher
343     $fh = IO::Handle->new();
344
345 Then use any of those as you would a normal filehandle.  Anywhere that
346 Perl is expecting a filehandle, an indirect filehandle may be used
347 instead. An indirect filehandle is just a scalar variable that contains
348 a filehandle.  Functions like C<print>, C<open>, C<seek>, or
349 the C<< <FH> >> diamond operator will accept either a read filehandle
350 or a scalar variable containing one:
351
352     ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
353     print $ofh "Type it: ";
354     $got = <$ifh>
355     print $efh "What was that: $got";
356
357 If you're passing a filehandle to a function, you can write
358 the function in two ways:
359
360     sub accept_fh {
361         my $fh = shift;
362         print $fh "Sending to indirect filehandle\n";
363     }
364
365 Or it can localize a typeglob and use the filehandle directly:
366
367     sub accept_fh {
368         local *FH = shift;
369         print  FH "Sending to localized filehandle\n";
370     }
371
372 Both styles work with either objects or typeglobs of real filehandles.
373 (They might also work with strings under some circumstances, but this
374 is risky.)
375
376     accept_fh(*STDOUT);
377     accept_fh($handle);
378
379 In the examples above, we assigned the filehandle to a scalar variable
380 before using it.  That is because only simple scalar variables, not
381 expressions or subscripts of hashes or arrays, can be used with
382 built-ins like C<print>, C<printf>, or the diamond operator.  Using
383 something other than a simple scalar variable as a filehandle is
384 illegal and won't even compile:
385
386     @fd = (*STDIN, *STDOUT, *STDERR);
387     print $fd[1] "Type it: ";                           # WRONG
388     $got = <$fd[0]>                                     # WRONG
389     print $fd[2] "What was that: $got";                 # WRONG
390
391 With C<print> and C<printf>, you get around this by using a block and
392 an expression where you would place the filehandle:
393
394     print  { $fd[1] } "funny stuff\n";
395     printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
396     # Pity the poor deadbeef.
397
398 That block is a proper block like any other, so you can put more
399 complicated code there.  This sends the message out to one of two places:
400
401     $ok = -x "/bin/cat";                
402     print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
403     print { $fd[ 1+ ($ok || 0) ]  } "cat stat $ok\n";           
404
405 This approach of treating C<print> and C<printf> like object methods
406 calls doesn't work for the diamond operator.  That's because it's a
407 real operator, not just a function with a comma-less argument.  Assuming
408 you've been storing typeglobs in your structure as we did above, you
409 can use the built-in function named C<readline> to reads a record just
410 as C<< <> >> does.  Given the initialization shown above for @fd, this
411 would work, but only because readline() require a typeglob.  It doesn't
412 work with objects or strings, which might be a bug we haven't fixed yet.
413
414     $got = readline($fd[0]);
415
416 Let it be noted that the flakiness of indirect filehandles is not
417 related to whether they're strings, typeglobs, objects, or anything else.
418 It's the syntax of the fundamental operators.  Playing the object
419 game doesn't help you at all here.
420
421 =head2 How can I set up a footer format to be used with write()?
422
423 There's no builtin way to do this, but L<perlform> has a couple of
424 techniques to make it possible for the intrepid hacker.
425
426 =head2 How can I write() into a string?
427
428 See L<perlform/"Accessing Formatting Internals"> for an swrite() function.
429
430 =head2 How can I output my numbers with commas added?
431
432 This one will do it for you:
433
434     sub commify {
435         my $number = shift;
436         1 while ($number =~ s/^([-+]?\d+)(\d{3})/$1,$2/);
437         return $number;
438     }
439
440     $n = 23659019423.2331;
441     print "GOT: ", commify($n), "\n";
442
443     GOT: 23,659,019,423.2331
444
445 You can't just:
446
447     s/^([-+]?\d+)(\d{3})/$1,$2/g;
448
449 because you have to put the comma in and then recalculate your
450 position.
451
452 Alternatively, this code commifies all numbers in a line regardless of
453 whether they have decimal portions, are preceded by + or -, or
454 whatever:
455
456     # from Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
457     sub commify {
458        my $input = shift;
459         $input = reverse $input;
460         $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
461         return scalar reverse $input;
462     }
463
464 =head2 How can I translate tildes (~) in a filename?
465
466 Use the <> (glob()) operator, documented in L<perlfunc>.  Older
467 versions of Perl require that you have a shell installed that groks
468 tildes.  Recent perl versions have this feature built in. The
469 File::KGlob module (available from CPAN) gives more portable glob
470 functionality.
471
472 Within Perl, you may use this directly:
473
474         $filename =~ s{
475           ^ ~             # find a leading tilde
476           (               # save this in $1
477               [^/]        # a non-slash character
478                     *     # repeated 0 or more times (0 means me)
479           )
480         }{
481           $1
482               ? (getpwnam($1))[7]
483               : ( $ENV{HOME} || $ENV{LOGDIR} )
484         }ex;
485
486 =head2 How come when I open a file read-write it wipes it out?
487
488 Because you're using something like this, which truncates the file and
489 I<then> gives you read-write access:
490
491     open(FH, "+> /path/name");          # WRONG (almost always)
492
493 Whoops.  You should instead use this, which will fail if the file
494 doesn't exist.  
495
496     open(FH, "+< /path/name");          # open for update
497
498 Using ">" always clobbers or creates.  Using "<" never does
499 either.  The "+" doesn't change this.
500
501 Here are examples of many kinds of file opens.  Those using sysopen()
502 all assume
503
504     use Fcntl;
505
506 To open file for reading:
507
508     open(FH, "< $path")                                 || die $!;
509     sysopen(FH, $path, O_RDONLY)                        || die $!;
510
511 To open file for writing, create new file if needed or else truncate old file:
512
513     open(FH, "> $path") || die $!;
514     sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT)        || die $!;
515     sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666)  || die $!;
516
517 To open file for writing, create new file, file must not exist:
518
519     sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT)         || die $!;
520     sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666)   || die $!;
521
522 To open file for appending, create if necessary:
523
524     open(FH, ">> $path") || die $!;
525     sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT)       || die $!;
526     sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;
527
528 To open file for appending, file must exist:
529
530     sysopen(FH, $path, O_WRONLY|O_APPEND)               || die $!;
531
532 To open file for update, file must exist:
533
534     open(FH, "+< $path")                                || die $!;
535     sysopen(FH, $path, O_RDWR)                          || die $!;
536
537 To open file for update, create file if necessary:
538
539     sysopen(FH, $path, O_RDWR|O_CREAT)                  || die $!;
540     sysopen(FH, $path, O_RDWR|O_CREAT, 0666)            || die $!;
541
542 To open file for update, file must not exist:
543
544     sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT)           || die $!;
545     sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666)     || die $!;
546
547 To open a file without blocking, creating if necessary:
548
549     sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT)
550             or die "can't open /tmp/somefile: $!":
551
552 Be warned that neither creation nor deletion of files is guaranteed to
553 be an atomic operation over NFS.  That is, two processes might both
554 successfully create or unlink the same file!  Therefore O_EXCL
555 isn't as exclusive as you might wish.
556
557 See also the new L<perlopentut> if you have it (new for 5.6).
558
559 =head2 Why do I sometimes get an "Argument list too long" when I use <*>?
560
561 The C<< <> >> operator performs a globbing operation (see above).
562 In Perl versions earlier than v5.6.0, the internal glob() operator forks
563 csh(1) to do the actual glob expansion, but
564 csh can't handle more than 127 items and so gives the error message
565 C<Argument list too long>.  People who installed tcsh as csh won't
566 have this problem, but their users may be surprised by it.
567
568 To get around this, either upgrade to Perl v5.6.0 or later, do the glob
569 yourself with readdir() and patterns, or use a module like File::KGlob,
570 one that doesn't use the shell to do globbing.
571
572 =head2 Is there a leak/bug in glob()?
573
574 Due to the current implementation on some operating systems, when you
575 use the glob() function or its angle-bracket alias in a scalar
576 context, you may cause a memory leak and/or unpredictable behavior.  It's
577 best therefore to use glob() only in list context.
578
579 =head2 How can I open a file with a leading ">" or trailing blanks?
580
581 Normally perl ignores trailing blanks in filenames, and interprets
582 certain leading characters (or a trailing "|") to mean something
583 special.  To avoid this, you might want to use a routine like the one below.
584 It turns incomplete pathnames into explicit relative ones, and tacks a
585 trailing null byte on the name to make perl leave it alone:
586
587     sub safe_filename {
588         local $_  = shift;
589         s#^([^./])#./$1#;
590         $_ .= "\0";
591         return $_;
592     }
593
594     $badpath = "<<<something really wicked   ";
595     $fn = safe_filename($badpath");
596     open(FH, "> $fn") or "couldn't open $badpath: $!";
597
598 This assumes that you are using POSIX (portable operating systems
599 interface) paths.  If you are on a closed, non-portable, proprietary
600 system, you may have to adjust the C<"./"> above.
601
602 It would be a lot clearer to use sysopen(), though:
603
604     use Fcntl;
605     $badpath = "<<<something really wicked   ";
606     sysopen (FH, $badpath, O_WRONLY | O_CREAT | O_TRUNC)
607         or die "can't open $badpath: $!";
608
609 For more information, see also the new L<perlopentut> if you have it
610 (new for 5.6).
611
612 =head2 How can I reliably rename a file?
613
614 If your operating system supports a proper mv(1) utility or its functional
615 equivalent, this works:
616
617     rename($old, $new) or system("mv", $old, $new);
618
619 It may be more portable to use the File::Copy module instead.
620 You just copy to the new file to the new name (checking return
621 values), then delete the old one.  This isn't really the same
622 semantically as a rename(), which preserves meta-information like
623 permissions, timestamps, inode info, etc.
624
625 Newer versions of File::Copy export a move() function.
626
627 =head2 How can I lock a file?
628
629 Perl's builtin flock() function (see L<perlfunc> for details) will call
630 flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and
631 later), and lockf(3) if neither of the two previous system calls exists.
632 On some systems, it may even use a different form of native locking.
633 Here are some gotchas with Perl's flock():
634
635 =over 4
636
637 =item 1
638
639 Produces a fatal error if none of the three system calls (or their
640 close equivalent) exists.
641
642 =item 2
643
644 lockf(3) does not provide shared locking, and requires that the
645 filehandle be open for writing (or appending, or read/writing).
646
647 =item 3
648
649 Some versions of flock() can't lock files over a network (e.g. on NFS file
650 systems), so you'd need to force the use of fcntl(2) when you build Perl.
651 But even this is dubious at best.  See the flock entry of L<perlfunc>
652 and the F<INSTALL> file in the source distribution for information on
653 building Perl to do this.
654
655 Two potentially non-obvious but traditional flock semantics are that
656 it waits indefinitely until the lock is granted, and that its locks are
657 I<merely advisory>.  Such discretionary locks are more flexible, but
658 offer fewer guarantees.  This means that files locked with flock() may
659 be modified by programs that do not also use flock().  Cars that stop
660 for red lights get on well with each other, but not with cars that don't
661 stop for red lights.  See the perlport manpage, your port's specific
662 documentation, or your system-specific local manpages for details.  It's
663 best to assume traditional behavior if you're writing portable programs.
664 (If you're not, you should as always feel perfectly free to write
665 for your own system's idiosyncrasies (sometimes called "features").
666 Slavish adherence to portability concerns shouldn't get in the way of
667 your getting your job done.)
668
669 For more information on file locking, see also 
670 L<perlopentut/"File Locking"> if you have it (new for 5.6).
671
672 =back
673
674 =head2 Why can't I just open(FH, ">file.lock")?
675
676 A common bit of code B<NOT TO USE> is this:
677
678     sleep(3) while -e "file.lock";      # PLEASE DO NOT USE
679     open(LCK, "> file.lock");           # THIS BROKEN CODE
680
681 This is a classic race condition: you take two steps to do something
682 which must be done in one.  That's why computer hardware provides an
683 atomic test-and-set instruction.   In theory, this "ought" to work:
684
685     sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT)
686                 or die "can't open  file.lock: $!":
687
688 except that lamentably, file creation (and deletion) is not atomic
689 over NFS, so this won't work (at least, not every time) over the net.
690 Various schemes involving link() have been suggested, but
691 these tend to involve busy-wait, which is also subdesirable.
692
693 =head2 I still don't get locking.  I just want to increment the number in the file.  How can I do this?
694
695 Didn't anyone ever tell you web-page hit counters were useless?
696 They don't count number of hits, they're a waste of time, and they serve
697 only to stroke the writer's vanity.  It's better to pick a random number;
698 they're more realistic.
699
700 Anyway, this is what you can do if you can't help yourself.
701
702     use Fcntl qw(:DEFAULT :flock);
703     sysopen(FH, "numfile", O_RDWR|O_CREAT)       or die "can't open numfile: $!";
704     flock(FH, LOCK_EX)                           or die "can't flock numfile: $!";
705     $num = <FH> || 0;
706     seek(FH, 0, 0)                               or die "can't rewind numfile: $!";
707     truncate(FH, 0)                              or die "can't truncate numfile: $!";
708     (print FH $num+1, "\n")                      or die "can't write numfile: $!";
709     close FH                                     or die "can't close numfile: $!";
710
711 Here's a much better web-page hit counter:
712
713     $hits = int( (time() - 850_000_000) / rand(1_000) );
714
715 If the count doesn't impress your friends, then the code might.  :-)
716
717 =head2 All I want to do is append a small amount of text to the end of a file.  Do I still have to use locking?
718
719 If you are on a system that correctly implements flock() and you use the
720 example appending code from "perldoc -f flock" everything will be OK
721 even if the OS you are on doesn't implement append mode correctly (if
722 such a system exists.) So if you are happy to restrict yourself to OSs
723 that implement flock() (and that's not really much of a restriction)
724 then that is what you should do.
725
726 If you know you are only going to use a system that does correctly
727 implement appending (i.e. not Win32) then you can omit the seek() from
728 the above code.
729
730 If you know you are only writing code to run on an OS and filesystem that
731 does implement append mode correctly (a local filesystem on a modern
732 Unix for example), and you keep the file in block-buffered mode and you
733 write less than one buffer-full of output between each manual flushing
734 of the buffer then each bufferload is almost guaranteed to be written to
735 the end of the file in one chunk without getting intermingled with
736 anyone else's output. You can also use the syswrite() function which is
737 simply a wrapper around your systems write(2) system call.
738
739 There is still a small theoretical chance that a signal will interrupt
740 the system level write() operation before completion.  There is also a
741 possibility that some STDIO implementations may call multiple system
742 level write()s even if the buffer was empty to start.  There may be some
743 systems where this probability is reduced to zero.
744
745 =head2 How do I randomly update a binary file?
746
747 If you're just trying to patch a binary, in many cases something as
748 simple as this works:
749
750     perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
751
752 However, if you have fixed sized records, then you might do something more
753 like this:
754
755     $RECSIZE = 220; # size of record, in bytes
756     $recno   = 37;  # which record to update
757     open(FH, "+<somewhere") || die "can't update somewhere: $!";
758     seek(FH, $recno * $RECSIZE, 0);
759     read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!";
760     # munge the record
761     seek(FH, -$RECSIZE, 1);
762     print FH $record;
763     close FH;
764
765 Locking and error checking are left as an exercise for the reader.
766 Don't forget them or you'll be quite sorry.
767
768 =head2 How do I get a file's timestamp in perl?
769
770 If you want to retrieve the time at which the file was last read,
771 written, or had its meta-data (owner, etc) changed, you use the B<-M>,
772 B<-A>, or B<-C> file test operations as documented in L<perlfunc>.  These
773 retrieve the age of the file (measured against the start-time of your
774 program) in days as a floating point number.  To retrieve the "raw"
775 time in seconds since the epoch, you would call the stat function,
776 then use localtime(), gmtime(), or POSIX::strftime() to convert this
777 into human-readable form.
778
779 Here's an example:
780
781     $write_secs = (stat($file))[9];
782     printf "file %s updated at %s\n", $file,
783         scalar localtime($write_secs);
784
785 If you prefer something more legible, use the File::stat module
786 (part of the standard distribution in version 5.004 and later):
787
788     # error checking left as an exercise for reader.
789     use File::stat;
790     use Time::localtime;
791     $date_string = ctime(stat($file)->mtime);
792     print "file $file updated at $date_string\n";
793
794 The POSIX::strftime() approach has the benefit of being,
795 in theory, independent of the current locale.  See L<perllocale>
796 for details.
797
798 =head2 How do I set a file's timestamp in perl?
799
800 You use the utime() function documented in L<perlfunc/utime>.
801 By way of example, here's a little program that copies the
802 read and write times from its first argument to all the rest
803 of them.
804
805     if (@ARGV < 2) {
806         die "usage: cptimes timestamp_file other_files ...\n";
807     }
808     $timestamp = shift;
809     ($atime, $mtime) = (stat($timestamp))[8,9];
810     utime $atime, $mtime, @ARGV;
811
812 Error checking is, as usual, left as an exercise for the reader.
813
814 Note that utime() currently doesn't work correctly with Win95/NT
815 ports.  A bug has been reported.  Check it carefully before using
816 utime() on those platforms.
817
818 =head2 How do I print to more than one file at once?
819
820 If you only have to do this once, you can do this:
821
822     for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
823
824 To connect up to one filehandle to several output filehandles, it's
825 easiest to use the tee(1) program if you have it, and let it take care
826 of the multiplexing:
827
828     open (FH, "| tee file1 file2 file3");
829
830 Or even:
831
832     # make STDOUT go to three files, plus original STDOUT
833     open (STDOUT, "| tee file1 file2 file3") or die "Teeing off: $!\n";
834     print "whatever\n"                       or die "Writing: $!\n";
835     close(STDOUT)                            or die "Closing: $!\n";
836
837 Otherwise you'll have to write your own multiplexing print
838 function--or your own tee program--or use Tom Christiansen's,
839 at http://www.cpan.org/authors/id/TOMC/scripts/tct.gz , which is
840 written in Perl and offers much greater functionality
841 than the stock version.
842
843 =head2 How can I read in an entire file all at once?
844
845 The customary Perl approach for processing all the lines in a file is to
846 do so one line at a time:
847
848     open (INPUT, $file)         || die "can't open $file: $!";
849     while (<INPUT>) {
850         chomp;
851         # do something with $_
852     } 
853     close(INPUT)                || die "can't close $file: $!";
854
855 This is tremendously more efficient than reading the entire file into
856 memory as an array of lines and then processing it one element at a time,
857 which is often--if not almost always--the wrong approach.  Whenever
858 you see someone do this:
859
860     @lines = <INPUT>;
861
862 you should think long and hard about why you need everything loaded
863 at once.  It's just not a scalable solution.  You might also find it
864 more fun to use the standard DB_File module's $DB_RECNO bindings,
865 which allow you to tie an array to a file so that accessing an element
866 the array actually accesses the corresponding line in the file.
867
868 On very rare occasion, you may have an algorithm that demands that
869 the entire file be in memory at once as one scalar.  The simplest solution
870 to that is
871
872     $var = `cat $file`;
873
874 Being in scalar context, you get the whole thing.  In list context,
875 you'd get a list of all the lines:
876
877     @lines = `cat $file`;
878
879 This tiny but expedient solution is neat, clean, and portable to
880 all systems on which decent tools have been installed.  For those
881 who prefer not to use the toolbox, you can of course read the file
882 manually, although this makes for more complicated code.
883
884     {
885         local(*INPUT, $/);
886         open (INPUT, $file)     || die "can't open $file: $!";
887         $var = <INPUT>;
888     }
889
890 That temporarily undefs your record separator, and will automatically 
891 close the file at block exit.  If the file is already open, just use this:
892
893     $var = do { local $/; <INPUT> };
894
895 =head2 How can I read in a file by paragraphs?
896
897 Use the C<$/> variable (see L<perlvar> for details).  You can either
898 set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,
899 for instance, gets treated as two paragraphs and not three), or
900 C<"\n\n"> to accept empty paragraphs.
901
902 Note that a blank line must have no blanks in it.  Thus 
903 S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two.
904
905 =head2 How can I read a single character from a file?  From the keyboard?
906
907 You can use the builtin C<getc()> function for most filehandles, but
908 it won't (easily) work on a terminal device.  For STDIN, either use
909 the Term::ReadKey module from CPAN or use the sample code in
910 L<perlfunc/getc>.
911
912 If your system supports the portable operating system programming
913 interface (POSIX), you can use the following code, which you'll note
914 turns off echo processing as well.
915
916     #!/usr/bin/perl -w
917     use strict;
918     $| = 1;
919     for (1..4) {
920         my $got;
921         print "gimme: ";
922         $got = getone();
923         print "--> $got\n";
924     }
925     exit;
926
927     BEGIN {
928         use POSIX qw(:termios_h);
929
930         my ($term, $oterm, $echo, $noecho, $fd_stdin);
931
932         $fd_stdin = fileno(STDIN);
933
934         $term     = POSIX::Termios->new();
935         $term->getattr($fd_stdin);
936         $oterm     = $term->getlflag();
937
938         $echo     = ECHO | ECHOK | ICANON;
939         $noecho   = $oterm & ~$echo;
940
941         sub cbreak {
942             $term->setlflag($noecho);
943             $term->setcc(VTIME, 1);
944             $term->setattr($fd_stdin, TCSANOW);
945         }
946
947         sub cooked {
948             $term->setlflag($oterm);
949             $term->setcc(VTIME, 0);
950             $term->setattr($fd_stdin, TCSANOW);
951         }
952
953         sub getone {
954             my $key = '';
955             cbreak();
956             sysread(STDIN, $key, 1);
957             cooked();
958             return $key;
959         }
960
961     }
962
963     END { cooked() }
964
965 The Term::ReadKey module from CPAN may be easier to use.  Recent versions
966 include also support for non-portable systems as well.
967
968     use Term::ReadKey;
969     open(TTY, "</dev/tty");
970     print "Gimme a char: ";
971     ReadMode "raw";
972     $key = ReadKey 0, *TTY;
973     ReadMode "normal";
974     printf "\nYou said %s, char number %03d\n",
975         $key, ord $key;
976
977 =head2 How can I tell whether there's a character waiting on a filehandle?
978
979 The very first thing you should do is look into getting the Term::ReadKey
980 extension from CPAN.  As we mentioned earlier, it now even has limited
981 support for non-portable (read: not open systems, closed, proprietary,
982 not POSIX, not Unix, etc) systems.
983
984 You should also check out the Frequently Asked Questions list in
985 comp.unix.* for things like this: the answer is essentially the same.
986 It's very system dependent.  Here's one solution that works on BSD
987 systems:
988
989     sub key_ready {
990         my($rin, $nfd);
991         vec($rin, fileno(STDIN), 1) = 1;
992         return $nfd = select($rin,undef,undef,0);
993     }
994
995 If you want to find out how many characters are waiting, there's
996 also the FIONREAD ioctl call to be looked at.  The I<h2ph> tool that
997 comes with Perl tries to convert C include files to Perl code, which
998 can be C<require>d.  FIONREAD ends up defined as a function in the
999 I<sys/ioctl.ph> file:
1000
1001     require 'sys/ioctl.ph';
1002
1003     $size = pack("L", 0);
1004     ioctl(FH, FIONREAD(), $size)    or die "Couldn't call ioctl: $!\n";
1005     $size = unpack("L", $size);
1006
1007 If I<h2ph> wasn't installed or doesn't work for you, you can
1008 I<grep> the include files by hand:
1009
1010     % grep FIONREAD /usr/include/*/*
1011     /usr/include/asm/ioctls.h:#define FIONREAD      0x541B
1012
1013 Or write a small C program using the editor of champions:
1014
1015     % cat > fionread.c
1016     #include <sys/ioctl.h>
1017     main() {
1018         printf("%#08x\n", FIONREAD);
1019     }
1020     ^D
1021     % cc -o fionread fionread.c
1022     % ./fionread
1023     0x4004667f
1024
1025 And then hard code it, leaving porting as an exercise to your successor.
1026
1027     $FIONREAD = 0x4004667f;         # XXX: opsys dependent
1028
1029     $size = pack("L", 0);
1030     ioctl(FH, $FIONREAD, $size)     or die "Couldn't call ioctl: $!\n";
1031     $size = unpack("L", $size);
1032
1033 FIONREAD requires a filehandle connected to a stream, meaning that sockets,
1034 pipes, and tty devices work, but I<not> files.
1035
1036 =head2 How do I do a C<tail -f> in perl?
1037
1038 First try
1039
1040     seek(GWFILE, 0, 1);
1041
1042 The statement C<seek(GWFILE, 0, 1)> doesn't change the current position,
1043 but it does clear the end-of-file condition on the handle, so that the
1044 next <GWFILE> makes Perl try again to read something.
1045
1046 If that doesn't work (it relies on features of your stdio implementation),
1047 then you need something more like this:
1048
1049         for (;;) {
1050           for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) {
1051             # search for some stuff and put it into files
1052           }
1053           # sleep for a while
1054           seek(GWFILE, $curpos, 0);  # seek to where we had been
1055         }
1056
1057 If this still doesn't work, look into the POSIX module.  POSIX defines
1058 the clearerr() method, which can remove the end of file condition on a
1059 filehandle.  The method: read until end of file, clearerr(), read some
1060 more.  Lather, rinse, repeat.
1061
1062 There's also a File::Tail module from CPAN.
1063
1064 =head2 How do I dup() a filehandle in Perl?
1065
1066 If you check L<perlfunc/open>, you'll see that several of the ways
1067 to call open() should do the trick.  For example:
1068
1069     open(LOG, ">>/tmp/logfile");
1070     open(STDERR, ">&LOG");
1071
1072 Or even with a literal numeric descriptor:
1073
1074    $fd = $ENV{MHCONTEXTFD};
1075    open(MHCONTEXT, "<&=$fd");   # like fdopen(3S)
1076
1077 Note that "<&STDIN" makes a copy, but "<&=STDIN" make
1078 an alias.  That means if you close an aliased handle, all
1079 aliases become inaccessible.  This is not true with 
1080 a copied one.
1081
1082 Error checking, as always, has been left as an exercise for the reader.
1083
1084 =head2 How do I close a file descriptor by number?
1085
1086 This should rarely be necessary, as the Perl close() function is to be
1087 used for things that Perl opened itself, even if it was a dup of a
1088 numeric descriptor as with MHCONTEXT above.  But if you really have
1089 to, you may be able to do this:
1090
1091     require 'sys/syscall.ph';
1092     $rc = syscall(&SYS_close, $fd + 0);  # must force numeric
1093     die "can't sysclose $fd: $!" unless $rc == -1;
1094
1095 Or, just use the fdopen(3S) feature of open():
1096
1097     { 
1098         local *F; 
1099         open F, "<&=$fd" or die "Cannot reopen fd=$fd: $!";
1100         close F;
1101     }
1102
1103 =head2 Why can't I use "C:\temp\foo" in DOS paths?  What doesn't `C:\temp\foo.exe` work?
1104
1105 Whoops!  You just put a tab and a formfeed into that filename!
1106 Remember that within double quoted strings ("like\this"), the
1107 backslash is an escape character.  The full list of these is in
1108 L<perlop/Quote and Quote-like Operators>.  Unsurprisingly, you don't
1109 have a file called "c:(tab)emp(formfeed)oo" or
1110 "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.
1111
1112 Either single-quote your strings, or (preferably) use forward slashes.
1113 Since all DOS and Windows versions since something like MS-DOS 2.0 or so
1114 have treated C</> and C<\> the same in a path, you might as well use the
1115 one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++,
1116 awk, Tcl, Java, or Python, just to mention a few.  POSIX paths
1117 are more portable, too.
1118
1119 =head2 Why doesn't glob("*.*") get all the files?
1120
1121 Because even on non-Unix ports, Perl's glob function follows standard
1122 Unix globbing semantics.  You'll need C<glob("*")> to get all (non-hidden)
1123 files.  This makes glob() portable even to legacy systems.  Your
1124 port may include proprietary globbing functions as well.  Check its
1125 documentation for details.
1126
1127 =head2 Why does Perl let me delete read-only files?  Why does C<-i> clobber protected files?  Isn't this a bug in Perl?
1128
1129 This is elaborately and painstakingly described in the
1130 F<file-dir-perms> article in the "Far More Than You Ever Wanted To
1131 Know" collection in http://www.cpan.org/olddoc/FMTEYEWTK.tgz .
1132
1133 The executive summary: learn how your filesystem works.  The
1134 permissions on a file say what can happen to the data in that file.
1135 The permissions on a directory say what can happen to the list of
1136 files in that directory.  If you delete a file, you're removing its
1137 name from the directory (so the operation depends on the permissions
1138 of the directory, not of the file).  If you try to write to the file,
1139 the permissions of the file govern whether you're allowed to.
1140
1141 =head2 How do I select a random line from a file?
1142
1143 Here's an algorithm from the Camel Book:
1144
1145     srand;
1146     rand($.) < 1 && ($line = $_) while <>;
1147
1148 This has a significant advantage in space over reading the whole
1149 file in.  A simple proof by induction is available upon 
1150 request if you doubt the algorithm's correctness.
1151
1152 =head2 Why do I get weird spaces when I print an array of lines?
1153
1154 Saying
1155
1156     print "@lines\n";
1157
1158 joins together the elements of C<@lines> with a space between them.
1159 If C<@lines> were C<("little", "fluffy", "clouds")> then the above
1160 statement would print
1161
1162     little fluffy clouds
1163
1164 but if each element of C<@lines> was a line of text, ending a newline
1165 character C<("little\n", "fluffy\n", "clouds\n")> then it would print:
1166
1167     little
1168      fluffy
1169      clouds
1170
1171 If your array contains lines, just print them:
1172
1173     print @lines;
1174
1175 =head1 AUTHOR AND COPYRIGHT
1176
1177 Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
1178 All rights reserved.
1179
1180 This documentation is free; you can redistribute it and/or modify it
1181 under the same terms as Perl itself.
1182
1183 Irrespective of its distribution, all code examples here are in the public
1184 domain.  You are permitted and encouraged to use this code and any
1185 derivatives thereof in your own programs for fun or for profit as you
1186 see fit.  A simple comment in the code giving credit to the FAQ would
1187 be courteous but is not required.