3 perlfaq5 - Files and Formats ($Revision: 1.9 $, $Date: 2002/02/11 19:30:21 $)
7 This section deals with I/O and the "f" issues: filehandles, flushing,
10 =head2 How do I flush/unbuffer an output filehandle? Why must I do this?
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
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.
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.
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>):
36 $old_fh = select(OUTPUT_HANDLE);
40 Or using the traditional idiom:
42 select((select(OUTPUT_HANDLE), $| = 1)[0]);
44 Or if don't mind slowly loading several thousand lines of module code
45 just because you're afraid of the C<$|> variable:
48 open(DEV, "+</dev/tty"); # ceci n'est pas une pipe
51 or the newer IO::* modules:
54 open(DEV, ">/dev/printer"); # but is this?
59 use IO::Socket; # this one is kinda a pipe?
60 $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.com',
61 PeerPort => 'http(80)',
63 die "$!" unless $sock;
66 print $sock "GET / HTTP/1.0" . "\015\012" x 2;
67 $document = join('', <$sock>);
68 print "DOC IS: $document\n";
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.
77 See L<perlfaq9> for other examples of fetching URLs over the web.
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?
81 Use the Tie::File module, which is included in the standard
82 distribution since Perl 5.8.0.
84 =head2 How do I count the number of lines in a file?
86 One fairly efficient way is to count newlines in the file. The
87 following program uses a feature of tr///, as documented in L<perlop>.
88 If your text file doesn't end with a newline, then it's not really a
89 proper text file, so this may report one fewer line than you expect.
92 open(FILE, $filename) or die "Can't open `$filename': $!";
93 while (sysread FILE, $buffer, 4096) {
94 $lines += ($buffer =~ tr/\n//);
98 This assumes no funny games with newline translations.
100 =head2 How do I make a temporary file name?
102 Use the File::Temp module, see L<File::Temp> for more information.
104 use File::Temp qw/ tempfile tempdir /;
106 $dir = tempdir( CLEANUP => 1 );
107 ($fh, $filename) = tempfile( DIR => $dir );
109 # or if you don't need to know the filename
111 $fh = tempfile( DIR => $dir );
113 The File::Temp has been a standard module since Perl 5.6.1. If you
114 don't have a modern enough Perl installed, use the C<new_tmpfile>
115 class method from the IO::File module to get a filehandle opened for
116 reading and writing. Use it if you don't need to know the file's name:
119 $fh = IO::File->new_tmpfile()
120 or die "Unable to make new temporary file: $!";
122 If you're committed to creating a temporary file by hand, use the
123 process ID and/or the current time-value. If you need to have many
124 temporary files in one process, use a counter:
128 my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
129 my $base_name = sprintf("%s/%d-%d-0000", $temp_dir, $$, time());
133 until (defined(fileno(FH)) || $count++ > 100) {
134 $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
135 sysopen(FH, $base_name, O_WRONLY|O_EXCL|O_CREAT);
137 if (defined(fileno(FH))
138 return (*FH, $base_name);
145 =head2 How can I manipulate fixed-record-length files?
147 The most efficient way is using pack() and unpack(). This is faster than
148 using substr() when taking many, many strings. It is slower for just a few.
150 Here is a sample chunk of code to break up and put back together again
151 some fixed-format input lines, in this case from the output of a normal,
155 # 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what
156 $PS_T = 'A6 A4 A7 A5 A*';
160 ($pid, $tt, $stat, $time, $command) = unpack($PS_T, $_);
161 for $var (qw!pid tt stat time command!) {
162 print "$var: <$$var>\n";
164 print 'line=', pack($PS_T, $pid, $tt, $stat, $time, $command),
168 We've used C<$$var> in a way that forbidden by C<use strict 'refs'>.
169 That is, we've promoted a string to a scalar variable reference using
170 symbolic references. This is okay in small programs, but doesn't scale
171 well. It also only works on global variables, not lexicals.
173 =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?
175 The fastest, simplest, and most direct way is to localize the typeglob
176 of the filehandle in question:
180 Typeglobs are fast (especially compared with the alternatives) and
181 reasonably easy to use, but they also have one subtle drawback. If you
182 had, for example, a function named TmpHandle(), or a variable named
183 %TmpHandle, you just hid it from yourself.
187 open(HostFile, "</etc/hosts") or die "no /etc/hosts: $!";
188 local $_; # <- VERY IMPORTANT
190 print if /\b127\.(0\.0\.)?1\b/;
192 # *HostFile automatically closes/disappears here
195 Here's how to use typeglobs in a loop to open and store a bunch of
196 filehandles. We'll use as values of the hash an ordered
197 pair to make it easy to sort the hash in insertion order.
199 @names = qw(motd termcap passwd hosts);
201 foreach $filename (@names) {
203 open(FH, "/etc/$filename") || die "$filename: $!";
204 $file{$filename} = [ $i++, *FH ];
207 # Using the filehandles in the array
208 foreach $name (sort { $file{$a}[0] <=> $file{$b}[0] } keys %file) {
209 my $fh = $file{$name}[1];
211 print "$name $. $line";
214 For passing filehandles to functions, the easiest way is to
215 preface them with a star, as in func(*STDIN).
216 See L<perlfaq7/"Passing Filehandles"> for details.
218 If you want to create many anonymous handles, you should check out the
219 Symbol, FileHandle, or IO::Handle (etc.) modules. Here's the equivalent
220 code with Symbol::gensym, which is reasonably light-weight:
222 foreach $filename (@names) {
225 open($fh, "/etc/$filename") || die "open /etc/$filename: $!";
226 $file{$filename} = [ $i++, $fh ];
229 Here's using the semi-object-oriented FileHandle module, which certainly
234 foreach $filename (@names) {
235 my $fh = FileHandle->new("/etc/$filename") or die "$filename: $!";
236 $file{$filename} = [ $i++, $fh ];
239 Please understand that whether the filehandle happens to be a (probably
240 localized) typeglob or an anonymous handle from one of the modules
241 in no way affects the bizarre rules for managing indirect handles.
242 See the next question.
244 =head2 How can I use a filehandle indirectly?
246 An indirect filehandle is using something other than a symbol
247 in a place that a filehandle is expected. Here are ways
248 to get indirect filehandles:
250 $fh = SOME_FH; # bareword is strict-subs hostile
251 $fh = "SOME_FH"; # strict-refs hostile; same package only
252 $fh = *SOME_FH; # typeglob
253 $fh = \*SOME_FH; # ref to typeglob (bless-able)
254 $fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob
256 Or, you can use the C<new> method from the FileHandle or IO modules to
257 create an anonymous filehandle, store that in a scalar variable,
258 and use it as though it were a normal filehandle.
261 $fh = FileHandle->new();
263 use IO::Handle; # 5.004 or higher
264 $fh = IO::Handle->new();
266 Then use any of those as you would a normal filehandle. Anywhere that
267 Perl is expecting a filehandle, an indirect filehandle may be used
268 instead. An indirect filehandle is just a scalar variable that contains
269 a filehandle. Functions like C<print>, C<open>, C<seek>, or
270 the C<< <FH> >> diamond operator will accept either a read filehandle
271 or a scalar variable containing one:
273 ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
274 print $ofh "Type it: ";
276 print $efh "What was that: $got";
278 If you're passing a filehandle to a function, you can write
279 the function in two ways:
283 print $fh "Sending to indirect filehandle\n";
286 Or it can localize a typeglob and use the filehandle directly:
290 print FH "Sending to localized filehandle\n";
293 Both styles work with either objects or typeglobs of real filehandles.
294 (They might also work with strings under some circumstances, but this
300 In the examples above, we assigned the filehandle to a scalar variable
301 before using it. That is because only simple scalar variables, not
302 expressions or subscripts of hashes or arrays, can be used with
303 built-ins like C<print>, C<printf>, or the diamond operator. Using
304 something other than a simple scalar variable as a filehandle is
305 illegal and won't even compile:
307 @fd = (*STDIN, *STDOUT, *STDERR);
308 print $fd[1] "Type it: "; # WRONG
309 $got = <$fd[0]> # WRONG
310 print $fd[2] "What was that: $got"; # WRONG
312 With C<print> and C<printf>, you get around this by using a block and
313 an expression where you would place the filehandle:
315 print { $fd[1] } "funny stuff\n";
316 printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
317 # Pity the poor deadbeef.
319 That block is a proper block like any other, so you can put more
320 complicated code there. This sends the message out to one of two places:
323 print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
324 print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n";
326 This approach of treating C<print> and C<printf> like object methods
327 calls doesn't work for the diamond operator. That's because it's a
328 real operator, not just a function with a comma-less argument. Assuming
329 you've been storing typeglobs in your structure as we did above, you
330 can use the built-in function named C<readline> to reads a record just
331 as C<< <> >> does. Given the initialization shown above for @fd, this
332 would work, but only because readline() require a typeglob. It doesn't
333 work with objects or strings, which might be a bug we haven't fixed yet.
335 $got = readline($fd[0]);
337 Let it be noted that the flakiness of indirect filehandles is not
338 related to whether they're strings, typeglobs, objects, or anything else.
339 It's the syntax of the fundamental operators. Playing the object
340 game doesn't help you at all here.
342 =head2 How can I set up a footer format to be used with write()?
344 There's no builtin way to do this, but L<perlform> has a couple of
345 techniques to make it possible for the intrepid hacker.
347 =head2 How can I write() into a string?
349 See L<perlform/"Accessing Formatting Internals"> for an swrite() function.
351 =head2 How can I output my numbers with commas added?
353 This one will do it for you:
357 1 while ($number =~ s/^([-+]?\d+)(\d{3})/$1,$2/);
361 $n = 23659019423.2331;
362 print "GOT: ", commify($n), "\n";
364 GOT: 23,659,019,423.2331
368 s/^([-+]?\d+)(\d{3})/$1,$2/g;
370 because you have to put the comma in and then recalculate your
373 Alternatively, this code commifies all numbers in a line regardless of
374 whether they have decimal portions, are preceded by + or -, or
377 # from Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
380 $input = reverse $input;
381 $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
382 return scalar reverse $input;
385 =head2 How can I translate tildes (~) in a filename?
387 Use the <> (glob()) operator, documented in L<perlfunc>. Older
388 versions of Perl require that you have a shell installed that groks
389 tildes. Recent perl versions have this feature built in. The
390 File::KGlob module (available from CPAN) gives more portable glob
393 Within Perl, you may use this directly:
396 ^ ~ # find a leading tilde
398 [^/] # a non-slash character
399 * # repeated 0 or more times (0 means me)
404 : ( $ENV{HOME} || $ENV{LOGDIR} )
407 =head2 How come when I open a file read-write it wipes it out?
409 Because you're using something like this, which truncates the file and
410 I<then> gives you read-write access:
412 open(FH, "+> /path/name"); # WRONG (almost always)
414 Whoops. You should instead use this, which will fail if the file
417 open(FH, "+< /path/name"); # open for update
419 Using ">" always clobbers or creates. Using "<" never does
420 either. The "+" doesn't change this.
422 Here are examples of many kinds of file opens. Those using sysopen()
427 To open file for reading:
429 open(FH, "< $path") || die $!;
430 sysopen(FH, $path, O_RDONLY) || die $!;
432 To open file for writing, create new file if needed or else truncate old file:
434 open(FH, "> $path") || die $!;
435 sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT) || die $!;
436 sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666) || die $!;
438 To open file for writing, create new file, file must not exist:
440 sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) || die $!;
441 sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666) || die $!;
443 To open file for appending, create if necessary:
445 open(FH, ">> $path") || die $!;
446 sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT) || die $!;
447 sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;
449 To open file for appending, file must exist:
451 sysopen(FH, $path, O_WRONLY|O_APPEND) || die $!;
453 To open file for update, file must exist:
455 open(FH, "+< $path") || die $!;
456 sysopen(FH, $path, O_RDWR) || die $!;
458 To open file for update, create file if necessary:
460 sysopen(FH, $path, O_RDWR|O_CREAT) || die $!;
461 sysopen(FH, $path, O_RDWR|O_CREAT, 0666) || die $!;
463 To open file for update, file must not exist:
465 sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) || die $!;
466 sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666) || die $!;
468 To open a file without blocking, creating if necessary:
470 sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT)
471 or die "can't open /tmp/somefile: $!":
473 Be warned that neither creation nor deletion of files is guaranteed to
474 be an atomic operation over NFS. That is, two processes might both
475 successfully create or unlink the same file! Therefore O_EXCL
476 isn't as exclusive as you might wish.
478 See also the new L<perlopentut> if you have it (new for 5.6).
480 =head2 Why do I sometimes get an "Argument list too long" when I use <*>?
482 The C<< <> >> operator performs a globbing operation (see above).
483 In Perl versions earlier than v5.6.0, the internal glob() operator forks
484 csh(1) to do the actual glob expansion, but
485 csh can't handle more than 127 items and so gives the error message
486 C<Argument list too long>. People who installed tcsh as csh won't
487 have this problem, but their users may be surprised by it.
489 To get around this, either upgrade to Perl v5.6.0 or later, do the glob
490 yourself with readdir() and patterns, or use a module like File::KGlob,
491 one that doesn't use the shell to do globbing.
493 =head2 Is there a leak/bug in glob()?
495 Due to the current implementation on some operating systems, when you
496 use the glob() function or its angle-bracket alias in a scalar
497 context, you may cause a memory leak and/or unpredictable behavior. It's
498 best therefore to use glob() only in list context.
500 =head2 How can I open a file with a leading ">" or trailing blanks?
502 Normally perl ignores trailing blanks in filenames, and interprets
503 certain leading characters (or a trailing "|") to mean something
504 special. To avoid this, you might want to use a routine like the one below.
505 It turns incomplete pathnames into explicit relative ones, and tacks a
506 trailing null byte on the name to make perl leave it alone:
515 $badpath = "<<<something really wicked ";
516 $fn = safe_filename($badpath");
517 open(FH, "> $fn") or "couldn't open $badpath: $!";
519 This assumes that you are using POSIX (portable operating systems
520 interface) paths. If you are on a closed, non-portable, proprietary
521 system, you may have to adjust the C<"./"> above.
523 It would be a lot clearer to use sysopen(), though:
526 $badpath = "<<<something really wicked ";
527 sysopen (FH, $badpath, O_WRONLY | O_CREAT | O_TRUNC)
528 or die "can't open $badpath: $!";
530 For more information, see also the new L<perlopentut> if you have it
533 =head2 How can I reliably rename a file?
535 If your operating system supports a proper mv(1) utility or its functional
536 equivalent, this works:
538 rename($old, $new) or system("mv", $old, $new);
540 It may be more portable to use the File::Copy module instead.
541 You just copy to the new file to the new name (checking return
542 values), then delete the old one. This isn't really the same
543 semantically as a rename(), which preserves meta-information like
544 permissions, timestamps, inode info, etc.
546 Newer versions of File::Copy export a move() function.
548 =head2 How can I lock a file?
550 Perl's builtin flock() function (see L<perlfunc> for details) will call
551 flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and
552 later), and lockf(3) if neither of the two previous system calls exists.
553 On some systems, it may even use a different form of native locking.
554 Here are some gotchas with Perl's flock():
560 Produces a fatal error if none of the three system calls (or their
561 close equivalent) exists.
565 lockf(3) does not provide shared locking, and requires that the
566 filehandle be open for writing (or appending, or read/writing).
570 Some versions of flock() can't lock files over a network (e.g. on NFS file
571 systems), so you'd need to force the use of fcntl(2) when you build Perl.
572 But even this is dubious at best. See the flock entry of L<perlfunc>
573 and the F<INSTALL> file in the source distribution for information on
574 building Perl to do this.
576 Two potentially non-obvious but traditional flock semantics are that
577 it waits indefinitely until the lock is granted, and that its locks are
578 I<merely advisory>. Such discretionary locks are more flexible, but
579 offer fewer guarantees. This means that files locked with flock() may
580 be modified by programs that do not also use flock(). Cars that stop
581 for red lights get on well with each other, but not with cars that don't
582 stop for red lights. See the perlport manpage, your port's specific
583 documentation, or your system-specific local manpages for details. It's
584 best to assume traditional behavior if you're writing portable programs.
585 (If you're not, you should as always feel perfectly free to write
586 for your own system's idiosyncrasies (sometimes called "features").
587 Slavish adherence to portability concerns shouldn't get in the way of
588 your getting your job done.)
590 For more information on file locking, see also
591 L<perlopentut/"File Locking"> if you have it (new for 5.6).
595 =head2 Why can't I just open(FH, ">file.lock")?
597 A common bit of code B<NOT TO USE> is this:
599 sleep(3) while -e "file.lock"; # PLEASE DO NOT USE
600 open(LCK, "> file.lock"); # THIS BROKEN CODE
602 This is a classic race condition: you take two steps to do something
603 which must be done in one. That's why computer hardware provides an
604 atomic test-and-set instruction. In theory, this "ought" to work:
606 sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT)
607 or die "can't open file.lock: $!":
609 except that lamentably, file creation (and deletion) is not atomic
610 over NFS, so this won't work (at least, not every time) over the net.
611 Various schemes involving link() have been suggested, but
612 these tend to involve busy-wait, which is also subdesirable.
614 =head2 I still don't get locking. I just want to increment the number in the file. How can I do this?
616 Didn't anyone ever tell you web-page hit counters were useless?
617 They don't count number of hits, they're a waste of time, and they serve
618 only to stroke the writer's vanity. It's better to pick a random number;
619 they're more realistic.
621 Anyway, this is what you can do if you can't help yourself.
623 use Fcntl qw(:DEFAULT :flock);
624 sysopen(FH, "numfile", O_RDWR|O_CREAT) or die "can't open numfile: $!";
625 flock(FH, LOCK_EX) or die "can't flock numfile: $!";
627 seek(FH, 0, 0) or die "can't rewind numfile: $!";
628 truncate(FH, 0) or die "can't truncate numfile: $!";
629 (print FH $num+1, "\n") or die "can't write numfile: $!";
630 close FH or die "can't close numfile: $!";
632 Here's a much better web-page hit counter:
634 $hits = int( (time() - 850_000_000) / rand(1_000) );
636 If the count doesn't impress your friends, then the code might. :-)
638 =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?
640 If you are on a system that correctly implements flock() and you use the
641 example appending code from "perldoc -f flock" everything will be OK
642 even if the OS you are on doesn't implement append mode correctly (if
643 such a system exists.) So if you are happy to restrict yourself to OSs
644 that implement flock() (and that's not really much of a restriction)
645 then that is what you should do.
647 If you know you are only going to use a system that does correctly
648 implement appending (i.e. not Win32) then you can omit the seek() from
651 If you know you are only writing code to run on an OS and filesystem that
652 does implement append mode correctly (a local filesystem on a modern
653 Unix for example), and you keep the file in block-buffered mode and you
654 write less than one buffer-full of output between each manual flushing
655 of the buffer then each bufferload is almost guaranteed to be written to
656 the end of the file in one chunk without getting intermingled with
657 anyone else's output. You can also use the syswrite() function which is
658 simply a wrapper around your systems write(2) system call.
660 There is still a small theoretical chance that a signal will interrupt
661 the system level write() operation before completion. There is also a
662 possibility that some STDIO implementations may call multiple system
663 level write()s even if the buffer was empty to start. There may be some
664 systems where this probability is reduced to zero.
666 =head2 How do I randomly update a binary file?
668 If you're just trying to patch a binary, in many cases something as
669 simple as this works:
671 perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
673 However, if you have fixed sized records, then you might do something more
676 $RECSIZE = 220; # size of record, in bytes
677 $recno = 37; # which record to update
678 open(FH, "+<somewhere") || die "can't update somewhere: $!";
679 seek(FH, $recno * $RECSIZE, 0);
680 read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!";
682 seek(FH, -$RECSIZE, 1);
686 Locking and error checking are left as an exercise for the reader.
687 Don't forget them or you'll be quite sorry.
689 =head2 How do I get a file's timestamp in perl?
691 If you want to retrieve the time at which the file was last read,
692 written, or had its meta-data (owner, etc) changed, you use the B<-M>,
693 B<-A>, or B<-C> file test operations as documented in L<perlfunc>. These
694 retrieve the age of the file (measured against the start-time of your
695 program) in days as a floating point number. To retrieve the "raw"
696 time in seconds since the epoch, you would call the stat function,
697 then use localtime(), gmtime(), or POSIX::strftime() to convert this
698 into human-readable form.
702 $write_secs = (stat($file))[9];
703 printf "file %s updated at %s\n", $file,
704 scalar localtime($write_secs);
706 If you prefer something more legible, use the File::stat module
707 (part of the standard distribution in version 5.004 and later):
709 # error checking left as an exercise for reader.
712 $date_string = ctime(stat($file)->mtime);
713 print "file $file updated at $date_string\n";
715 The POSIX::strftime() approach has the benefit of being,
716 in theory, independent of the current locale. See L<perllocale>
719 =head2 How do I set a file's timestamp in perl?
721 You use the utime() function documented in L<perlfunc/utime>.
722 By way of example, here's a little program that copies the
723 read and write times from its first argument to all the rest
727 die "usage: cptimes timestamp_file other_files ...\n";
730 ($atime, $mtime) = (stat($timestamp))[8,9];
731 utime $atime, $mtime, @ARGV;
733 Error checking is, as usual, left as an exercise for the reader.
735 Note that utime() currently doesn't work correctly with Win95/NT
736 ports. A bug has been reported. Check it carefully before using
737 utime() on those platforms.
739 =head2 How do I print to more than one file at once?
741 If you only have to do this once, you can do this:
743 for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
745 To connect up to one filehandle to several output filehandles, it's
746 easiest to use the tee(1) program if you have it, and let it take care
749 open (FH, "| tee file1 file2 file3");
753 # make STDOUT go to three files, plus original STDOUT
754 open (STDOUT, "| tee file1 file2 file3") or die "Teeing off: $!\n";
755 print "whatever\n" or die "Writing: $!\n";
756 close(STDOUT) or die "Closing: $!\n";
758 Otherwise you'll have to write your own multiplexing print
759 function--or your own tee program--or use Tom Christiansen's,
760 at http://www.cpan.org/authors/id/TOMC/scripts/tct.gz , which is
761 written in Perl and offers much greater functionality
762 than the stock version.
764 =head2 How can I read in an entire file all at once?
766 The customary Perl approach for processing all the lines in a file is to
767 do so one line at a time:
769 open (INPUT, $file) || die "can't open $file: $!";
772 # do something with $_
774 close(INPUT) || die "can't close $file: $!";
776 This is tremendously more efficient than reading the entire file into
777 memory as an array of lines and then processing it one element at a time,
778 which is often--if not almost always--the wrong approach. Whenever
779 you see someone do this:
783 you should think long and hard about why you need everything loaded
784 at once. It's just not a scalable solution. You might also find it
785 more fun to use the standard DB_File module's $DB_RECNO bindings,
786 which allow you to tie an array to a file so that accessing an element
787 the array actually accesses the corresponding line in the file.
789 On very rare occasion, you may have an algorithm that demands that
790 the entire file be in memory at once as one scalar. The simplest solution
795 Being in scalar context, you get the whole thing. In list context,
796 you'd get a list of all the lines:
798 @lines = `cat $file`;
800 This tiny but expedient solution is neat, clean, and portable to
801 all systems on which decent tools have been installed. For those
802 who prefer not to use the toolbox, you can of course read the file
803 manually, although this makes for more complicated code.
807 open (INPUT, $file) || die "can't open $file: $!";
811 That temporarily undefs your record separator, and will automatically
812 close the file at block exit. If the file is already open, just use this:
814 $var = do { local $/; <INPUT> };
816 =head2 How can I read in a file by paragraphs?
818 Use the C<$/> variable (see L<perlvar> for details). You can either
819 set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,
820 for instance, gets treated as two paragraphs and not three), or
821 C<"\n\n"> to accept empty paragraphs.
823 Note that a blank line must have no blanks in it. Thus
824 S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two.
826 =head2 How can I read a single character from a file? From the keyboard?
828 You can use the builtin C<getc()> function for most filehandles, but
829 it won't (easily) work on a terminal device. For STDIN, either use
830 the Term::ReadKey module from CPAN or use the sample code in
833 If your system supports the portable operating system programming
834 interface (POSIX), you can use the following code, which you'll note
835 turns off echo processing as well.
849 use POSIX qw(:termios_h);
851 my ($term, $oterm, $echo, $noecho, $fd_stdin);
853 $fd_stdin = fileno(STDIN);
855 $term = POSIX::Termios->new();
856 $term->getattr($fd_stdin);
857 $oterm = $term->getlflag();
859 $echo = ECHO | ECHOK | ICANON;
860 $noecho = $oterm & ~$echo;
863 $term->setlflag($noecho);
864 $term->setcc(VTIME, 1);
865 $term->setattr($fd_stdin, TCSANOW);
869 $term->setlflag($oterm);
870 $term->setcc(VTIME, 0);
871 $term->setattr($fd_stdin, TCSANOW);
877 sysread(STDIN, $key, 1);
886 The Term::ReadKey module from CPAN may be easier to use. Recent versions
887 include also support for non-portable systems as well.
890 open(TTY, "</dev/tty");
891 print "Gimme a char: ";
893 $key = ReadKey 0, *TTY;
895 printf "\nYou said %s, char number %03d\n",
898 =head2 How can I tell whether there's a character waiting on a filehandle?
900 The very first thing you should do is look into getting the Term::ReadKey
901 extension from CPAN. As we mentioned earlier, it now even has limited
902 support for non-portable (read: not open systems, closed, proprietary,
903 not POSIX, not Unix, etc) systems.
905 You should also check out the Frequently Asked Questions list in
906 comp.unix.* for things like this: the answer is essentially the same.
907 It's very system dependent. Here's one solution that works on BSD
912 vec($rin, fileno(STDIN), 1) = 1;
913 return $nfd = select($rin,undef,undef,0);
916 If you want to find out how many characters are waiting, there's
917 also the FIONREAD ioctl call to be looked at. The I<h2ph> tool that
918 comes with Perl tries to convert C include files to Perl code, which
919 can be C<require>d. FIONREAD ends up defined as a function in the
920 I<sys/ioctl.ph> file:
922 require 'sys/ioctl.ph';
924 $size = pack("L", 0);
925 ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n";
926 $size = unpack("L", $size);
928 If I<h2ph> wasn't installed or doesn't work for you, you can
929 I<grep> the include files by hand:
931 % grep FIONREAD /usr/include/*/*
932 /usr/include/asm/ioctls.h:#define FIONREAD 0x541B
934 Or write a small C program using the editor of champions:
937 #include <sys/ioctl.h>
939 printf("%#08x\n", FIONREAD);
942 % cc -o fionread fionread.c
946 And then hard code it, leaving porting as an exercise to your successor.
948 $FIONREAD = 0x4004667f; # XXX: opsys dependent
950 $size = pack("L", 0);
951 ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n";
952 $size = unpack("L", $size);
954 FIONREAD requires a filehandle connected to a stream, meaning that sockets,
955 pipes, and tty devices work, but I<not> files.
957 =head2 How do I do a C<tail -f> in perl?
963 The statement C<seek(GWFILE, 0, 1)> doesn't change the current position,
964 but it does clear the end-of-file condition on the handle, so that the
965 next <GWFILE> makes Perl try again to read something.
967 If that doesn't work (it relies on features of your stdio implementation),
968 then you need something more like this:
971 for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) {
972 # search for some stuff and put it into files
975 seek(GWFILE, $curpos, 0); # seek to where we had been
978 If this still doesn't work, look into the POSIX module. POSIX defines
979 the clearerr() method, which can remove the end of file condition on a
980 filehandle. The method: read until end of file, clearerr(), read some
981 more. Lather, rinse, repeat.
983 There's also a File::Tail module from CPAN.
985 =head2 How do I dup() a filehandle in Perl?
987 If you check L<perlfunc/open>, you'll see that several of the ways
988 to call open() should do the trick. For example:
990 open(LOG, ">>/tmp/logfile");
991 open(STDERR, ">&LOG");
993 Or even with a literal numeric descriptor:
995 $fd = $ENV{MHCONTEXTFD};
996 open(MHCONTEXT, "<&=$fd"); # like fdopen(3S)
998 Note that "<&STDIN" makes a copy, but "<&=STDIN" make
999 an alias. That means if you close an aliased handle, all
1000 aliases become inaccessible. This is not true with
1003 Error checking, as always, has been left as an exercise for the reader.
1005 =head2 How do I close a file descriptor by number?
1007 This should rarely be necessary, as the Perl close() function is to be
1008 used for things that Perl opened itself, even if it was a dup of a
1009 numeric descriptor as with MHCONTEXT above. But if you really have
1010 to, you may be able to do this:
1012 require 'sys/syscall.ph';
1013 $rc = syscall(&SYS_close, $fd + 0); # must force numeric
1014 die "can't sysclose $fd: $!" unless $rc == -1;
1016 Or, just use the fdopen(3S) feature of open():
1020 open F, "<&=$fd" or die "Cannot reopen fd=$fd: $!";
1024 =head2 Why can't I use "C:\temp\foo" in DOS paths? What doesn't `C:\temp\foo.exe` work?
1026 Whoops! You just put a tab and a formfeed into that filename!
1027 Remember that within double quoted strings ("like\this"), the
1028 backslash is an escape character. The full list of these is in
1029 L<perlop/Quote and Quote-like Operators>. Unsurprisingly, you don't
1030 have a file called "c:(tab)emp(formfeed)oo" or
1031 "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.
1033 Either single-quote your strings, or (preferably) use forward slashes.
1034 Since all DOS and Windows versions since something like MS-DOS 2.0 or so
1035 have treated C</> and C<\> the same in a path, you might as well use the
1036 one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++,
1037 awk, Tcl, Java, or Python, just to mention a few. POSIX paths
1038 are more portable, too.
1040 =head2 Why doesn't glob("*.*") get all the files?
1042 Because even on non-Unix ports, Perl's glob function follows standard
1043 Unix globbing semantics. You'll need C<glob("*")> to get all (non-hidden)
1044 files. This makes glob() portable even to legacy systems. Your
1045 port may include proprietary globbing functions as well. Check its
1046 documentation for details.
1048 =head2 Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl?
1050 This is elaborately and painstakingly described in the
1051 F<file-dir-perms> article in the "Far More Than You Ever Wanted To
1052 Know" collection in http://www.cpan.org/olddoc/FMTEYEWTK.tgz .
1054 The executive summary: learn how your filesystem works. The
1055 permissions on a file say what can happen to the data in that file.
1056 The permissions on a directory say what can happen to the list of
1057 files in that directory. If you delete a file, you're removing its
1058 name from the directory (so the operation depends on the permissions
1059 of the directory, not of the file). If you try to write to the file,
1060 the permissions of the file govern whether you're allowed to.
1062 =head2 How do I select a random line from a file?
1064 Here's an algorithm from the Camel Book:
1067 rand($.) < 1 && ($line = $_) while <>;
1069 This has a significant advantage in space over reading the whole
1070 file in. A simple proof by induction is available upon
1071 request if you doubt the algorithm's correctness.
1073 =head2 Why do I get weird spaces when I print an array of lines?
1079 joins together the elements of C<@lines> with a space between them.
1080 If C<@lines> were C<("little", "fluffy", "clouds")> then the above
1081 statement would print
1083 little fluffy clouds
1085 but if each element of C<@lines> was a line of text, ending a newline
1086 character C<("little\n", "fluffy\n", "clouds\n")> then it would print:
1092 If your array contains lines, just print them:
1096 =head1 AUTHOR AND COPYRIGHT
1098 Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
1099 All rights reserved.
1101 This documentation is free; you can redistribute it and/or modify it
1102 under the same terms as Perl itself.
1104 Irrespective of its distribution, all code examples here are in the public
1105 domain. You are permitted and encouraged to use this code and any
1106 derivatives thereof in your own programs for fun or for profit as you
1107 see fit. A simple comment in the code giving credit to the FAQ would
1108 be courteous but is not required.