3 perlfaq5 - Files and Formats
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?
11 X<flush> X<buffer> X<unbuffer> X<autoflush>
13 (contributed by brian d foy)
15 You might like to read Mark Jason Dominus's "Suffering From Buffering"
16 at http://perl.plover.com/FAQs/Buffering.html .
18 Perl normally buffers output so it doesn't make a system call for every
19 bit of output. By saving up output, it makes fewer expensive system calls.
20 For instance, in this little bit of code, you want to print a dot to the
21 screen for every line you process to watch the progress of your program.
22 Instead of seeing a dot for every line, Perl buffers the output and you
23 have a long wait before you see a row of 50 dots all at once:
25 # long wait, then row of dots all at once
28 print "\n" unless ++$count % 50;
30 #... expensive line processing operations
33 To get around this, you have to unbuffer the output filehandle, in this
34 case, C<STDOUT>. You can set the special variable C<$|> to a true value
35 (mnemonic: making your filehandles "piping hot"):
39 # dot shown immediately
42 print "\n" unless ++$count % 50;
44 #... expensive line processing operations
47 The C<$|> is one of the per-filehandle special variables, so each
48 filehandle has its own copy of its value. If you want to merge
49 standard output and standard error for instance, you have to unbuffer
50 each (although STDERR might be unbuffered by default):
53 my $previous_default = select(STDOUT); # save previous default
54 $|++; # autoflush STDOUT
56 $|++; # autoflush STDERR, to be sure
57 select($previous_default); # restore previous default
60 # now should alternate . and +
66 print STDOUT "\n" unless ++$count % 25;
69 Besides the C<$|> special variable, you can use C<binmode> to give
70 your filehandle a C<:unix> layer, which is unbuffered:
72 binmode( STDOUT, ":unix" );
77 print "\n" unless ++$count % 50;
80 For more information on output layers, see the entries for C<binmode>
81 and C<open> in L<perlfunc>, and the C<PerlIO> module documentation.
83 If you are using C<IO::Handle> or one of its subclasses, you can
84 call the C<autoflush> method to change the settings of the
88 open my( $io_fh ), ">", "output.txt";
91 The C<IO::Handle> objects also have a C<flush> method. You can flush
92 the buffer any time you want without auto-buffering
96 =head2 How do I change, delete, or insert a line in a file, or append to the beginning of a file?
99 (contributed by brian d foy)
101 The basic idea of inserting, changing, or deleting a line from a text
102 file involves reading and printing the file to the point you want to
103 make the change, making the change, then reading and printing the rest
104 of the file. Perl doesn't provide random access to lines (especially
105 since the record input separator, C<$/>, is mutable), although modules
106 such as C<Tie::File> can fake it.
108 A Perl program to do these tasks takes the basic form of opening a
109 file, printing its lines, then closing the file:
111 open my $in, '<', $file or die "Can't read old file: $!";
112 open my $out, '>', "$file.new" or die "Can't write new file: $!";
121 Within that basic form, add the parts that you need to insert, change,
124 To prepend lines to the beginning, print those lines before you enter
125 the loop that prints the existing lines.
127 open my $in, '<', $file or die "Can't read old file: $!";
128 open my $out, '>', "$file.new" or die "Can't write new file: $!";
130 print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC
139 To change existing lines, insert the code to modify the lines inside
140 the C<while> loop. In this case, the code finds all lowercased
141 versions of "perl" and uppercases them. The happens for every line, so
142 be sure that you're supposed to do that on every line!
144 open my $in, '<', $file or die "Can't read old file: $!";
145 open my $out, '>', "$file.new" or die "Can't write new file: $!";
147 print $out "# Add this line to the top\n";
157 To change only a particular line, the input line number, C<$.>, is
158 useful. First read and print the lines up to the one you want to
159 change. Next, read the single line you want to change, change it, and
160 print it. After that, read the rest of the lines and print those:
162 while( <$in> ) # print the lines before the change
165 last if $. == 4; # line number before change
169 $line =~ s/\b(perl)\b/Perl/g;
172 while( <$in> ) # print the rest of the lines
177 To skip lines, use the looping controls. The C<next> in this example
178 skips comment lines, and the C<last> stops all processing once it
179 encounters either C<__END__> or C<__DATA__>.
183 next if /^\s+#/; # skip comment lines
184 last if /^__(END|DATA)__$/; # stop at end of code marker
188 Do the same sort of thing to delete a particular line by using C<next>
189 to skip the lines you don't want to show up in the output. This
190 example skips every fifth line:
198 If, for some odd reason, you really want to see the whole file at once
199 rather than processing line-by-line, you can slurp it in (as long as
200 you can fit the whole thing in memory!):
202 open my $in, '<', $file or die "Can't read old file: $!"
203 open my $out, '>', "$file.new" or die "Can't write new file: $!";
205 my @lines = do { local $/; <$in> }; # slurp!
211 Modules such as C<File::Slurp> and C<Tie::File> can help with that
212 too. If you can, however, avoid reading the entire file at once. Perl
213 won't give that memory back to the operating system until the process
216 You can also use Perl one-liners to modify a file in-place. The
217 following changes all 'Fred' to 'Barney' in F<inFile.txt>, overwriting
218 the file with the new contents. With the C<-p> switch, Perl wraps a
219 C<while> loop around the code you specify with C<-e>, and C<-i> turns
220 on in-place editing. The current line is in C<$_>. With C<-p>, Perl
221 automatically prints the value of C<$_> at the end of the loop. See
222 L<perlrun> for more details.
224 perl -pi -e 's/Fred/Barney/' inFile.txt
226 To make a backup of C<inFile.txt>, give C<-i> a file extension to add:
228 perl -pi.bak -e 's/Fred/Barney/' inFile.txt
230 To change only the fifth line, you can add a test checking C<$.>, the
231 input line number, then only perform the operation when the test
234 perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
236 To add lines before a certain line, you can add a line (or lines!)
237 before Perl prints C<$_>:
239 perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
241 You can even add a line to the beginning of a file, since the current
242 line prints at the end of the loop:
244 perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
246 To insert a line after one already in the file, use the C<-n> switch.
247 It's just like C<-p> except that it doesn't print C<$_> at the end of
248 the loop, so you have to do that yourself. In this case, print C<$_>
249 first, then print the line that you want to add.
251 perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
253 To delete lines, only print the ones that you want.
255 perl -ni -e 'print unless /d/' inFile.txt
259 perl -pi -e 'next unless /d/' inFile.txt
261 =head2 How do I count the number of lines in a file?
262 X<file, counting lines> X<lines> X<line>
264 One fairly efficient way is to count newlines in the file. The
265 following program uses a feature of tr///, as documented in L<perlop>.
266 If your text file doesn't end with a newline, then it's not really a
267 proper text file, so this may report one fewer line than you expect.
270 open(FILE, $filename) or die "Can't open `$filename': $!";
271 while (sysread FILE, $buffer, 4096) {
272 $lines += ($buffer =~ tr/\n//);
276 This assumes no funny games with newline translations.
278 =head2 How do I delete the last N lines from a file?
281 (contributed by brian d foy)
283 The easiest conceptual solution is to count the lines in the
284 file then start at the beginning and print the number of lines
285 (minus the last N) to a new file.
287 Most often, the real question is how you can delete the last N
288 lines without making more than one pass over the file, or how to
289 do it with a lot of copying. The easy concept is the hard reality when
290 you might have millions of lines in your file.
292 One trick is to use C<File::ReadBackwards>, which starts at the end of
293 the file. That module provides an object that wraps the real filehandle
294 to make it easy for you to move around the file. Once you get to the
295 spot you need, you can get the actual filehandle and work with it as
296 normal. In this case, you get the file position at the end of the last
297 line you want to keep and truncate the file to that point:
299 use File::ReadBackwards;
301 my $filename = 'test.txt';
302 my $Lines_to_truncate = 2;
304 my $bw = File::ReadBackwards->new( $filename )
305 or die "Could not read backwards in [$filename]: $!";
307 my $lines_from_end = 0;
308 until( $bw->eof or $lines_from_end == $Lines_to_truncate )
310 print "Got: ", $bw->readline;
314 truncate( $filename, $bw->tell );
316 The C<File::ReadBackwards> module also has the advantage of setting
317 the input record separator to a regular expression.
319 You can also use the C<Tie::File> module which lets you access
320 the lines through a tied array. You can use normal array operations
321 to modify your file, including setting the last index and using
324 =head2 How can I use Perl's C<-i> option from within a program?
327 C<-i> sets the value of Perl's C<$^I> variable, which in turn affects
328 the behavior of C<< <> >>; see L<perlrun> for more details. By
329 modifying the appropriate variables directly, you can get the same
330 behavior within a larger program. For example:
334 local($^I, @ARGV) = ('.orig', glob("*.c"));
337 print "This line should appear at the top of each file\n";
339 s/\b(p)earl\b/${1}erl/i; # Correct typos, preserving case
341 close ARGV if eof; # Reset $.
344 # $^I and @ARGV return to their old values here
346 This block modifies all the C<.c> files in the current directory,
347 leaving a backup of the original data from each file in a new
350 =head2 How can I copy a file?
351 X<copy> X<file, copy> X<File::Copy>
353 (contributed by brian d foy)
355 Use the C<File::Copy> module. It comes with Perl and can do a
356 true copy across file systems, and it does its magic in
361 copy( $original, $new_copy ) or die "Copy failed: $!";
363 If you can't use C<File::Copy>, you'll have to do the work yourself:
364 open the original file, open the destination file, then print
365 to the destination file as you read the original. You also have to
366 remember to copy the permissions, owner, and group to the new file.
368 =head2 How do I make a temporary file name?
371 If you don't need to know the name of the file, you can use C<open()>
372 with C<undef> in place of the file name. In Perl 5.8 or later, the
373 C<open()> function creates an anonymous temporary file:
375 open my $tmp, '+>', undef or die $!;
377 Otherwise, you can use the File::Temp module.
379 use File::Temp qw/ tempfile tempdir /;
381 $dir = tempdir( CLEANUP => 1 );
382 ($fh, $filename) = tempfile( DIR => $dir );
384 # or if you don't need to know the filename
386 $fh = tempfile( DIR => $dir );
388 The File::Temp has been a standard module since Perl 5.6.1. If you
389 don't have a modern enough Perl installed, use the C<new_tmpfile>
390 class method from the IO::File module to get a filehandle opened for
391 reading and writing. Use it if you don't need to know the file's name:
394 $fh = IO::File->new_tmpfile()
395 or die "Unable to make new temporary file: $!";
397 If you're committed to creating a temporary file by hand, use the
398 process ID and/or the current time-value. If you need to have many
399 temporary files in one process, use a counter:
403 my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
404 my $base_name = sprintf "%s/%d-%d-0000", $temp_dir, $$, time;
409 until( defined(fileno(FH)) || $count++ > 100 ) {
410 $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
411 # O_EXCL is required for security reasons.
412 sysopen FH, $base_name, O_WRONLY|O_EXCL|O_CREAT;
415 if( defined fileno(FH) ) {
416 return (*FH, $base_name);
425 =head2 How can I manipulate fixed-record-length files?
426 X<fixed-length> X<file, fixed-length records>
428 The most efficient way is using L<pack()|perlfunc/"pack"> and
429 L<unpack()|perlfunc/"unpack">. This is faster than using
430 L<substr()|perlfunc/"substr"> when taking many, many strings. It is
431 slower for just a few.
433 Here is a sample chunk of code to break up and put back together again
434 some fixed-format input lines, in this case from the output of a normal,
438 # 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what
439 my $PS_T = 'A6 A4 A7 A5 A*';
440 open my $ps, '-|', 'ps';
442 my @fields = qw( pid tt stat time command );
445 @process{@fields} = unpack($PS_T, $_);
446 for my $field ( @fields ) {
447 print "$field: <$process{$field}>\n";
449 print 'line=', pack($PS_T, @process{@fields} ), "\n";
452 We've used a hash slice in order to easily handle the fields of each row.
453 Storing the keys in an array means it's easy to operate on them as a
454 group or loop over them with for. It also avoids polluting the program
455 with global variables and using symbolic references.
457 =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?
458 X<filehandle, local> X<filehandle, passing> X<filehandle, reference>
460 As of perl5.6, open() autovivifies file and directory handles
461 as references if you pass it an uninitialized scalar variable.
462 You can then pass these references just like any other scalar,
463 and use them in the place of named handles.
465 open my $fh, $file_name;
467 open local $fh, $file_name;
469 print $fh "Hello World!\n";
473 If you like, you can store these filehandles in an array or a hash.
474 If you access them directly, they aren't simple scalars and you
475 need to give C<print> a little help by placing the filehandle
476 reference in braces. Perl can only figure it out on its own when
477 the filehandle reference is a simple scalar.
479 my @fhs = ( $fh1, $fh2, $fh3 );
481 for( $i = 0; $i <= $#fhs; $i++ ) {
482 print {$fhs[$i]} "just another Perl answer, \n";
485 Before perl5.6, you had to deal with various typeglob idioms
486 which you may see in older code.
488 open FILE, "> $filename";
489 process_typeglob( *FILE );
490 process_reference( \*FILE );
492 sub process_typeglob { local *FH = shift; print FH "Typeglob!" }
493 sub process_reference { local $fh = shift; print $fh "Reference!" }
495 If you want to create many anonymous handles, you should
496 check out the Symbol or IO::Handle modules.
498 =head2 How can I use a filehandle indirectly?
499 X<filehandle, indirect>
501 An indirect filehandle is using something other than a symbol
502 in a place that a filehandle is expected. Here are ways
503 to get indirect filehandles:
505 $fh = SOME_FH; # bareword is strict-subs hostile
506 $fh = "SOME_FH"; # strict-refs hostile; same package only
507 $fh = *SOME_FH; # typeglob
508 $fh = \*SOME_FH; # ref to typeglob (bless-able)
509 $fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob
511 Or, you can use the C<new> method from one of the IO::* modules to
512 create an anonymous filehandle, store that in a scalar variable,
513 and use it as though it were a normal filehandle.
515 use IO::Handle; # 5.004 or higher
516 $fh = IO::Handle->new();
518 Then use any of those as you would a normal filehandle. Anywhere that
519 Perl is expecting a filehandle, an indirect filehandle may be used
520 instead. An indirect filehandle is just a scalar variable that contains
521 a filehandle. Functions like C<print>, C<open>, C<seek>, or
522 the C<< <FH> >> diamond operator will accept either a named filehandle
523 or a scalar variable containing one:
525 ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
526 print $ofh "Type it: ";
528 print $efh "What was that: $got";
530 If you're passing a filehandle to a function, you can write
531 the function in two ways:
535 print $fh "Sending to indirect filehandle\n";
538 Or it can localize a typeglob and use the filehandle directly:
542 print FH "Sending to localized filehandle\n";
545 Both styles work with either objects or typeglobs of real filehandles.
546 (They might also work with strings under some circumstances, but this
552 In the examples above, we assigned the filehandle to a scalar variable
553 before using it. That is because only simple scalar variables, not
554 expressions or subscripts of hashes or arrays, can be used with
555 built-ins like C<print>, C<printf>, or the diamond operator. Using
556 something other than a simple scalar variable as a filehandle is
557 illegal and won't even compile:
559 @fd = (*STDIN, *STDOUT, *STDERR);
560 print $fd[1] "Type it: "; # WRONG
561 $got = <$fd[0]> # WRONG
562 print $fd[2] "What was that: $got"; # WRONG
564 With C<print> and C<printf>, you get around this by using a block and
565 an expression where you would place the filehandle:
567 print { $fd[1] } "funny stuff\n";
568 printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
569 # Pity the poor deadbeef.
571 That block is a proper block like any other, so you can put more
572 complicated code there. This sends the message out to one of two places:
575 print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
576 print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n";
578 This approach of treating C<print> and C<printf> like object methods
579 calls doesn't work for the diamond operator. That's because it's a
580 real operator, not just a function with a comma-less argument. Assuming
581 you've been storing typeglobs in your structure as we did above, you
582 can use the built-in function named C<readline> to read a record just
583 as C<< <> >> does. Given the initialization shown above for @fd, this
584 would work, but only because readline() requires a typeglob. It doesn't
585 work with objects or strings, which might be a bug we haven't fixed yet.
587 $got = readline($fd[0]);
589 Let it be noted that the flakiness of indirect filehandles is not
590 related to whether they're strings, typeglobs, objects, or anything else.
591 It's the syntax of the fundamental operators. Playing the object
592 game doesn't help you at all here.
594 =head2 How can I set up a footer format to be used with write()?
597 There's no builtin way to do this, but L<perlform> has a couple of
598 techniques to make it possible for the intrepid hacker.
600 =head2 How can I write() into a string?
601 X<write, into a string>
603 See L<perlform/"Accessing Formatting Internals"> for an C<swrite()> function.
605 =head2 How can I open a filehandle to a string?
606 X<string> X<open> X<IO::String> X<filehandle>
608 (contributed by Peter J. Holzer, hjp-usenet2@hjp.at)
610 Since Perl 5.8.0 a file handle referring to a string can be created by
611 calling open with a reference to that string instead of the filename.
612 This file handle can then be used to read from or write to the string:
614 open(my $fh, '>', \$string) or die "Could not open string for writing";
616 print $fh "bar\n"; # $string now contains "foo\nbar\n"
618 open(my $fh, '<', \$string) or die "Could not open string for reading";
619 my $x = <$fh>; # $x now contains "foo\n"
621 With older versions of Perl, the C<IO::String> module provides similar
624 =head2 How can I output my numbers with commas added?
627 (contributed by brian d foy and Benjamin Goldberg)
629 You can use L<Number::Format> to separate places in a number.
630 It handles locale information for those of you who want to insert
631 full stops instead (or anything else that they want to use,
634 This subroutine will add commas to your number:
638 1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
642 This regex from Benjamin Goldberg will add commas to numbers:
644 s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
646 It is easier to see with comments:
649 ^[-+]? # beginning of number.
650 \d+? # first digits before first comma
651 (?= # followed by, (but not included in the match) :
652 (?>(?:\d{3})+) # some positive multiple of three digits.
653 (?!\d) # an *exact* multiple, not x * 3 + 1 or whatever.
656 \G\d{3} # after the last group, get three digits
657 (?=\d) # but they have to have more digits after them.
660 =head2 How can I translate tildes (~) in a filename?
661 X<tilde> X<tilde expansion>
663 Use the E<lt>E<gt> (C<glob()>) operator, documented in L<perlfunc>.
664 Versions of Perl older than 5.6 require that you have a shell
665 installed that groks tildes. Later versions of Perl have this feature
666 built in. The C<File::KGlob> module (available from CPAN) gives more
667 portable glob functionality.
669 Within Perl, you may use this directly:
672 ^ ~ # find a leading tilde
674 [^/] # a non-slash character
675 * # repeated 0 or more times (0 means me)
680 : ( $ENV{HOME} || $ENV{LOGDIR} )
683 =head2 How come when I open a file read-write it wipes it out?
684 X<clobber> X<read-write> X<clobbering> X<truncate> X<truncating>
686 Because you're using something like this, which truncates the file and
687 I<then> gives you read-write access:
689 open(FH, "+> /path/name"); # WRONG (almost always)
691 Whoops. You should instead use this, which will fail if the file
694 open(FH, "+< /path/name"); # open for update
696 Using ">" always clobbers or creates. Using "<" never does
697 either. The "+" doesn't change this.
699 Here are examples of many kinds of file opens. Those using sysopen()
704 To open file for reading:
706 open(FH, "< $path") || die $!;
707 sysopen(FH, $path, O_RDONLY) || die $!;
709 To open file for writing, create new file if needed or else truncate old file:
711 open(FH, "> $path") || die $!;
712 sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT) || die $!;
713 sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666) || die $!;
715 To open file for writing, create new file, file must not exist:
717 sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) || die $!;
718 sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666) || die $!;
720 To open file for appending, create if necessary:
722 open(FH, ">> $path") || die $!;
723 sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT) || die $!;
724 sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;
726 To open file for appending, file must exist:
728 sysopen(FH, $path, O_WRONLY|O_APPEND) || die $!;
730 To open file for update, file must exist:
732 open(FH, "+< $path") || die $!;
733 sysopen(FH, $path, O_RDWR) || die $!;
735 To open file for update, create file if necessary:
737 sysopen(FH, $path, O_RDWR|O_CREAT) || die $!;
738 sysopen(FH, $path, O_RDWR|O_CREAT, 0666) || die $!;
740 To open file for update, file must not exist:
742 sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) || die $!;
743 sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666) || die $!;
745 To open a file without blocking, creating if necessary:
747 sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT)
748 or die "can't open /foo/somefile: $!":
750 Be warned that neither creation nor deletion of files is guaranteed to
751 be an atomic operation over NFS. That is, two processes might both
752 successfully create or unlink the same file! Therefore O_EXCL
753 isn't as exclusive as you might wish.
755 See also the new L<perlopentut> if you have it (new for 5.6).
757 =head2 Why do I sometimes get an "Argument list too long" when I use E<lt>*E<gt>?
758 X<argument list too long>
760 The C<< <> >> operator performs a globbing operation (see above).
761 In Perl versions earlier than v5.6.0, the internal glob() operator forks
762 csh(1) to do the actual glob expansion, but
763 csh can't handle more than 127 items and so gives the error message
764 C<Argument list too long>. People who installed tcsh as csh won't
765 have this problem, but their users may be surprised by it.
767 To get around this, either upgrade to Perl v5.6.0 or later, do the glob
768 yourself with readdir() and patterns, or use a module like File::KGlob,
769 one that doesn't use the shell to do globbing.
771 =head2 Is there a leak/bug in glob()?
774 (contributed by brian d foy)
776 Starting with Perl 5.6.0, C<glob> is implemented internally rather
777 than relying on an external resource. As such, memory issues with
778 C<glob> aren't a problem in modern perls.
780 =head2 How can I open a file with a leading ">" or trailing blanks?
781 X<filename, special characters>
783 (contributed by Brian McCauley)
785 The special two argument form of Perl's open() function ignores
786 trailing blanks in filenames and infers the mode from certain leading
787 characters (or a trailing "|"). In older versions of Perl this was the
788 only version of open() and so it is prevalent in old code and books.
790 Unless you have a particular reason to use the two argument form you
791 should use the three argument form of open() which does not treat any
792 characters in the filename as special.
794 open FILE, "<", " file "; # filename is " file "
795 open FILE, ">", ">file"; # filename is ">file"
797 =head2 How can I reliably rename a file?
798 X<rename> X<mv> X<move> X<file, rename>
800 If your operating system supports a proper mv(1) utility or its
801 functional equivalent, this works:
803 rename($old, $new) or system("mv", $old, $new);
805 It may be more portable to use the C<File::Copy> module instead.
806 You just copy to the new file to the new name (checking return
807 values), then delete the old one. This isn't really the same
808 semantically as a C<rename()>, which preserves meta-information like
809 permissions, timestamps, inode info, etc.
811 =head2 How can I lock a file?
812 X<lock> X<file, lock> X<flock>
814 Perl's builtin flock() function (see L<perlfunc> for details) will call
815 flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and
816 later), and lockf(3) if neither of the two previous system calls exists.
817 On some systems, it may even use a different form of native locking.
818 Here are some gotchas with Perl's flock():
824 Produces a fatal error if none of the three system calls (or their
825 close equivalent) exists.
829 lockf(3) does not provide shared locking, and requires that the
830 filehandle be open for writing (or appending, or read/writing).
834 Some versions of flock() can't lock files over a network (e.g. on NFS file
835 systems), so you'd need to force the use of fcntl(2) when you build Perl.
836 But even this is dubious at best. See the flock entry of L<perlfunc>
837 and the F<INSTALL> file in the source distribution for information on
838 building Perl to do this.
840 Two potentially non-obvious but traditional flock semantics are that
841 it waits indefinitely until the lock is granted, and that its locks are
842 I<merely advisory>. Such discretionary locks are more flexible, but
843 offer fewer guarantees. This means that files locked with flock() may
844 be modified by programs that do not also use flock(). Cars that stop
845 for red lights get on well with each other, but not with cars that don't
846 stop for red lights. See the perlport manpage, your port's specific
847 documentation, or your system-specific local manpages for details. It's
848 best to assume traditional behavior if you're writing portable programs.
849 (If you're not, you should as always feel perfectly free to write
850 for your own system's idiosyncrasies (sometimes called "features").
851 Slavish adherence to portability concerns shouldn't get in the way of
852 your getting your job done.)
854 For more information on file locking, see also
855 L<perlopentut/"File Locking"> if you have it (new for 5.6).
859 =head2 Why can't I just open(FH, "E<gt>file.lock")?
860 X<lock, lockfile race condition>
862 A common bit of code B<NOT TO USE> is this:
864 sleep(3) while -e "file.lock"; # PLEASE DO NOT USE
865 open(LCK, "> file.lock"); # THIS BROKEN CODE
867 This is a classic race condition: you take two steps to do something
868 which must be done in one. That's why computer hardware provides an
869 atomic test-and-set instruction. In theory, this "ought" to work:
871 sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT)
872 or die "can't open file.lock: $!";
874 except that lamentably, file creation (and deletion) is not atomic
875 over NFS, so this won't work (at least, not every time) over the net.
876 Various schemes involving link() have been suggested, but
877 these tend to involve busy-wait, which is also less than desirable.
879 =head2 I still don't get locking. I just want to increment the number in the file. How can I do this?
880 X<counter> X<file, counter>
882 Didn't anyone ever tell you web-page hit counters were useless?
883 They don't count number of hits, they're a waste of time, and they serve
884 only to stroke the writer's vanity. It's better to pick a random number;
885 they're more realistic.
887 Anyway, this is what you can do if you can't help yourself.
889 use Fcntl qw(:DEFAULT :flock);
890 sysopen(FH, "numfile", O_RDWR|O_CREAT) or die "can't open numfile: $!";
891 flock(FH, LOCK_EX) or die "can't flock numfile: $!";
893 seek(FH, 0, 0) or die "can't rewind numfile: $!";
894 truncate(FH, 0) or die "can't truncate numfile: $!";
895 (print FH $num+1, "\n") or die "can't write numfile: $!";
896 close FH or die "can't close numfile: $!";
898 Here's a much better web-page hit counter:
900 $hits = int( (time() - 850_000_000) / rand(1_000) );
902 If the count doesn't impress your friends, then the code might. :-)
904 =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?
905 X<append> X<file, append>
907 If you are on a system that correctly implements C<flock> and you use
908 the example appending code from "perldoc -f flock" everything will be
909 OK even if the OS you are on doesn't implement append mode correctly
910 (if such a system exists.) So if you are happy to restrict yourself to
911 OSs that implement C<flock> (and that's not really much of a
912 restriction) then that is what you should do.
914 If you know you are only going to use a system that does correctly
915 implement appending (i.e. not Win32) then you can omit the C<seek>
916 from the code in the previous answer.
918 If you know you are only writing code to run on an OS and filesystem
919 that does implement append mode correctly (a local filesystem on a
920 modern Unix for example), and you keep the file in block-buffered mode
921 and you write less than one buffer-full of output between each manual
922 flushing of the buffer then each bufferload is almost guaranteed to be
923 written to the end of the file in one chunk without getting
924 intermingled with anyone else's output. You can also use the
925 C<syswrite> function which is simply a wrapper around your system's
926 C<write(2)> system call.
928 There is still a small theoretical chance that a signal will interrupt
929 the system level C<write()> operation before completion. There is also
930 a possibility that some STDIO implementations may call multiple system
931 level C<write()>s even if the buffer was empty to start. There may be
932 some systems where this probability is reduced to zero, and this is
933 not a concern when using C<:perlio> instead of your system's STDIO.
935 =head2 How do I randomly update a binary file?
936 X<file, binary patch>
938 If you're just trying to patch a binary, in many cases something as
939 simple as this works:
941 perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
943 However, if you have fixed sized records, then you might do something more
946 $RECSIZE = 220; # size of record, in bytes
947 $recno = 37; # which record to update
948 open(FH, "+<somewhere") || die "can't update somewhere: $!";
949 seek(FH, $recno * $RECSIZE, 0);
950 read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!";
952 seek(FH, -$RECSIZE, 1);
956 Locking and error checking are left as an exercise for the reader.
957 Don't forget them or you'll be quite sorry.
959 =head2 How do I get a file's timestamp in perl?
960 X<timestamp> X<file, timestamp>
962 If you want to retrieve the time at which the file was last read,
963 written, or had its meta-data (owner, etc) changed, you use the B<-A>,
964 B<-M>, or B<-C> file test operations as documented in L<perlfunc>.
965 These retrieve the age of the file (measured against the start-time of
966 your program) in days as a floating point number. Some platforms may
967 not have all of these times. See L<perlport> for details. To retrieve
968 the "raw" time in seconds since the epoch, you would call the stat
969 function, then use C<localtime()>, C<gmtime()>, or
970 C<POSIX::strftime()> to convert this into human-readable form.
974 $write_secs = (stat($file))[9];
975 printf "file %s updated at %s\n", $file,
976 scalar localtime($write_secs);
978 If you prefer something more legible, use the File::stat module
979 (part of the standard distribution in version 5.004 and later):
981 # error checking left as an exercise for reader.
984 $date_string = ctime(stat($file)->mtime);
985 print "file $file updated at $date_string\n";
987 The POSIX::strftime() approach has the benefit of being,
988 in theory, independent of the current locale. See L<perllocale>
991 =head2 How do I set a file's timestamp in perl?
992 X<timestamp> X<file, timestamp>
994 You use the utime() function documented in L<perlfunc/utime>.
995 By way of example, here's a little program that copies the
996 read and write times from its first argument to all the rest
1000 die "usage: cptimes timestamp_file other_files ...\n";
1003 ($atime, $mtime) = (stat($timestamp))[8,9];
1004 utime $atime, $mtime, @ARGV;
1006 Error checking is, as usual, left as an exercise for the reader.
1008 The perldoc for utime also has an example that has the same
1009 effect as touch(1) on files that I<already exist>.
1011 Certain file systems have a limited ability to store the times
1012 on a file at the expected level of precision. For example, the
1013 FAT and HPFS filesystem are unable to create dates on files with
1014 a finer granularity than two seconds. This is a limitation of
1015 the filesystems, not of utime().
1017 =head2 How do I print to more than one file at once?
1018 X<print, to multiple files>
1020 To connect one filehandle to several output filehandles,
1021 you can use the IO::Tee or Tie::FileHandle::Multiplex modules.
1023 If you only have to do this once, you can print individually
1026 for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
1028 =head2 How can I read in an entire file all at once?
1029 X<slurp> X<file, slurping>
1031 You can use the File::Slurp module to do it in one step.
1035 $all_of_it = read_file($filename); # entire file in scalar
1036 @all_lines = read_file($filename); # one line per element
1038 The customary Perl approach for processing all the lines in a file is to
1039 do so one line at a time:
1041 open (INPUT, $file) || die "can't open $file: $!";
1044 # do something with $_
1046 close(INPUT) || die "can't close $file: $!";
1048 This is tremendously more efficient than reading the entire file into
1049 memory as an array of lines and then processing it one element at a time,
1050 which is often--if not almost always--the wrong approach. Whenever
1051 you see someone do this:
1055 you should think long and hard about why you need everything loaded at
1056 once. It's just not a scalable solution. You might also find it more
1057 fun to use the standard Tie::File module, or the DB_File module's
1058 $DB_RECNO bindings, which allow you to tie an array to a file so that
1059 accessing an element the array actually accesses the corresponding
1062 You can read the entire filehandle contents into a scalar.
1066 open (INPUT, $file) || die "can't open $file: $!";
1070 That temporarily undefs your record separator, and will automatically
1071 close the file at block exit. If the file is already open, just use this:
1073 $var = do { local $/; <INPUT> };
1075 For ordinary files you can also use the read function.
1077 read( INPUT, $var, -s INPUT );
1079 The third argument tests the byte size of the data on the INPUT filehandle
1080 and reads that many bytes into the buffer $var.
1082 =head2 How can I read in a file by paragraphs?
1083 X<file, reading by paragraphs>
1085 Use the C<$/> variable (see L<perlvar> for details). You can either
1086 set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,
1087 for instance, gets treated as two paragraphs and not three), or
1088 C<"\n\n"> to accept empty paragraphs.
1090 Note that a blank line must have no blanks in it. Thus
1091 S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two.
1093 =head2 How can I read a single character from a file? From the keyboard?
1094 X<getc> X<file, reading one character at a time>
1096 You can use the builtin C<getc()> function for most filehandles, but
1097 it won't (easily) work on a terminal device. For STDIN, either use
1098 the Term::ReadKey module from CPAN or use the sample code in
1101 If your system supports the portable operating system programming
1102 interface (POSIX), you can use the following code, which you'll note
1103 turns off echo processing as well.
1117 use POSIX qw(:termios_h);
1119 my ($term, $oterm, $echo, $noecho, $fd_stdin);
1121 $fd_stdin = fileno(STDIN);
1123 $term = POSIX::Termios->new();
1124 $term->getattr($fd_stdin);
1125 $oterm = $term->getlflag();
1127 $echo = ECHO | ECHOK | ICANON;
1128 $noecho = $oterm & ~$echo;
1131 $term->setlflag($noecho);
1132 $term->setcc(VTIME, 1);
1133 $term->setattr($fd_stdin, TCSANOW);
1137 $term->setlflag($oterm);
1138 $term->setcc(VTIME, 0);
1139 $term->setattr($fd_stdin, TCSANOW);
1145 sysread(STDIN, $key, 1);
1154 The Term::ReadKey module from CPAN may be easier to use. Recent versions
1155 include also support for non-portable systems as well.
1158 open(TTY, "</dev/tty");
1159 print "Gimme a char: ";
1161 $key = ReadKey 0, *TTY;
1163 printf "\nYou said %s, char number %03d\n",
1166 =head2 How can I tell whether there's a character waiting on a filehandle?
1168 The very first thing you should do is look into getting the Term::ReadKey
1169 extension from CPAN. As we mentioned earlier, it now even has limited
1170 support for non-portable (read: not open systems, closed, proprietary,
1171 not POSIX, not Unix, etc.) systems.
1173 You should also check out the Frequently Asked Questions list in
1174 comp.unix.* for things like this: the answer is essentially the same.
1175 It's very system dependent. Here's one solution that works on BSD
1180 vec($rin, fileno(STDIN), 1) = 1;
1181 return $nfd = select($rin,undef,undef,0);
1184 If you want to find out how many characters are waiting, there's
1185 also the FIONREAD ioctl call to be looked at. The I<h2ph> tool that
1186 comes with Perl tries to convert C include files to Perl code, which
1187 can be C<require>d. FIONREAD ends up defined as a function in the
1188 I<sys/ioctl.ph> file:
1190 require 'sys/ioctl.ph';
1192 $size = pack("L", 0);
1193 ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n";
1194 $size = unpack("L", $size);
1196 If I<h2ph> wasn't installed or doesn't work for you, you can
1197 I<grep> the include files by hand:
1199 % grep FIONREAD /usr/include/*/*
1200 /usr/include/asm/ioctls.h:#define FIONREAD 0x541B
1202 Or write a small C program using the editor of champions:
1205 #include <sys/ioctl.h>
1207 printf("%#08x\n", FIONREAD);
1210 % cc -o fionread fionread.c
1214 And then hard code it, leaving porting as an exercise to your successor.
1216 $FIONREAD = 0x4004667f; # XXX: opsys dependent
1218 $size = pack("L", 0);
1219 ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n";
1220 $size = unpack("L", $size);
1222 FIONREAD requires a filehandle connected to a stream, meaning that sockets,
1223 pipes, and tty devices work, but I<not> files.
1225 =head2 How do I do a C<tail -f> in perl?
1226 X<tail> X<IO::Handle> X<File::Tail> X<clearerr>
1232 The statement C<seek(GWFILE, 0, 1)> doesn't change the current position,
1233 but it does clear the end-of-file condition on the handle, so that the
1234 next C<< <GWFILE> >> makes Perl try again to read something.
1236 If that doesn't work (it relies on features of your stdio implementation),
1237 then you need something more like this:
1240 for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) {
1241 # search for some stuff and put it into files
1244 seek(GWFILE, $curpos, 0); # seek to where we had been
1247 If this still doesn't work, look into the C<clearerr> method
1248 from C<IO::Handle>, which resets the error and end-of-file states
1251 There's also a C<File::Tail> module from CPAN.
1253 =head2 How do I dup() a filehandle in Perl?
1256 If you check L<perlfunc/open>, you'll see that several of the ways
1257 to call open() should do the trick. For example:
1259 open(LOG, ">>/foo/logfile");
1260 open(STDERR, ">&LOG");
1262 Or even with a literal numeric descriptor:
1264 $fd = $ENV{MHCONTEXTFD};
1265 open(MHCONTEXT, "<&=$fd"); # like fdopen(3S)
1267 Note that "<&STDIN" makes a copy, but "<&=STDIN" make
1268 an alias. That means if you close an aliased handle, all
1269 aliases become inaccessible. This is not true with
1272 Error checking, as always, has been left as an exercise for the reader.
1274 =head2 How do I close a file descriptor by number?
1275 X<file, closing file descriptors> X<POSIX> X<close>
1277 If, for some reason, you have a file descriptor instead of a
1278 filehandle (perhaps you used C<POSIX::open>), you can use the
1279 C<close()> function from the C<POSIX> module:
1283 POSIX::close( $fd );
1285 This should rarely be necessary, as the Perl C<close()> function is to be
1286 used for things that Perl opened itself, even if it was a dup of a
1287 numeric descriptor as with C<MHCONTEXT> above. But if you really have
1288 to, you may be able to do this:
1290 require 'sys/syscall.ph';
1291 $rc = syscall(&SYS_close, $fd + 0); # must force numeric
1292 die "can't sysclose $fd: $!" unless $rc == -1;
1294 Or, just use the fdopen(3S) feature of C<open()>:
1297 open my( $fh ), "<&=$fd" or die "Cannot reopen fd=$fd: $!";
1301 =head2 Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
1302 X<filename, DOS issues>
1304 Whoops! You just put a tab and a formfeed into that filename!
1305 Remember that within double quoted strings ("like\this"), the
1306 backslash is an escape character. The full list of these is in
1307 L<perlop/Quote and Quote-like Operators>. Unsurprisingly, you don't
1308 have a file called "c:(tab)emp(formfeed)oo" or
1309 "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.
1311 Either single-quote your strings, or (preferably) use forward slashes.
1312 Since all DOS and Windows versions since something like MS-DOS 2.0 or so
1313 have treated C</> and C<\> the same in a path, you might as well use the
1314 one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++,
1315 awk, Tcl, Java, or Python, just to mention a few. POSIX paths
1316 are more portable, too.
1318 =head2 Why doesn't glob("*.*") get all the files?
1321 Because even on non-Unix ports, Perl's glob function follows standard
1322 Unix globbing semantics. You'll need C<glob("*")> to get all (non-hidden)
1323 files. This makes glob() portable even to legacy systems. Your
1324 port may include proprietary globbing functions as well. Check its
1325 documentation for details.
1327 =head2 Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl?
1329 This is elaborately and painstakingly described in the
1330 F<file-dir-perms> article in the "Far More Than You Ever Wanted To
1331 Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .
1333 The executive summary: learn how your filesystem works. The
1334 permissions on a file say what can happen to the data in that file.
1335 The permissions on a directory say what can happen to the list of
1336 files in that directory. If you delete a file, you're removing its
1337 name from the directory (so the operation depends on the permissions
1338 of the directory, not of the file). If you try to write to the file,
1339 the permissions of the file govern whether you're allowed to.
1341 =head2 How do I select a random line from a file?
1342 X<file, selecting a random line>
1344 Short of loading the file into a database or pre-indexing the lines in
1345 the file, there are a couple of things that you can do.
1347 Here's a reservoir-sampling algorithm from the Camel Book:
1350 rand($.) < 1 && ($line = $_) while <>;
1352 This has a significant advantage in space over reading the whole file
1353 in. You can find a proof of this method in I<The Art of Computer
1354 Programming>, Volume 2, Section 3.4.2, by Donald E. Knuth.
1356 You can use the C<File::Random> module which provides a function
1359 use File::Random qw/random_line/;
1360 my $line = random_line($filename);
1362 Another way is to use the C<Tie::File> module, which treats the entire
1363 file as an array. Simply access a random array element.
1365 =head2 Why do I get weird spaces when I print an array of lines?
1367 (contributed by brian d foy)
1369 If you are seeing spaces between the elements of your array when
1370 you print the array, you are probably interpolating the array in
1373 my @animals = qw(camel llama alpaca vicuna);
1374 print "animals are: @animals\n";
1376 It's the double quotes, not the C<print>, doing this. Whenever you
1377 interpolate an array in a double quote context, Perl joins the
1378 elements with spaces (or whatever is in C<$">, which is a space by
1381 animals are: camel llama alpaca vicuna
1383 This is different than printing the array without the interpolation:
1385 my @animals = qw(camel llama alpaca vicuna);
1386 print "animals are: ", @animals, "\n";
1388 Now the output doesn't have the spaces between the elements because
1389 the elements of C<@animals> simply become part of the list to
1392 animals are: camelllamaalpacavicuna
1394 You might notice this when each of the elements of C<@array> end with
1395 a newline. You expect to print one element per line, but notice that
1396 every line after the first is indented:
1399 this is another line
1400 this is the third line
1402 That extra space comes from the interpolation of the array. If you
1403 don't want to put anything between your array elements, don't use the
1404 array in double quotes. You can send it to print without them:
1408 =head2 How do I traverse a directory tree?
1410 (contributed by brian d foy)
1412 The C<File::Find> module, which comes with Perl, does all of the hard
1413 work to traverse a directory structure. It comes with Perl. You simply
1414 call the C<find> subroutine with a callback subroutine and the
1415 directories you want to traverse:
1419 find( \&wanted, @directories );
1422 # full path in $File::Find::name
1423 # just filename in $_
1424 ... do whatever you want to do ...
1427 The C<File::Find::Closures>, which you can download from CPAN, provides
1428 many ready-to-use subroutines that you can use with C<File::Find>.
1430 The C<File::Finder>, which you can download from CPAN, can help you
1431 create the callback subroutine using something closer to the syntax of
1432 the C<find> command-line utility:
1437 my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');
1439 find( $deep_dirs->as_options, @places );
1441 The C<File::Find::Rule> module, which you can download from CPAN, has
1442 a similar interface, but does the traversal for you too:
1444 use File::Find::Rule;
1446 my @files = File::Find::Rule->file()
1450 =head2 How do I delete a directory tree?
1452 (contributed by brian d foy)
1454 If you have an empty directory, you can use Perl's built-in C<rmdir>. If
1455 the directory is not empty (so, no files or subdirectories), you either
1456 have to empty it yourself (a lot of work) or use a module to help you.
1458 The C<File::Path> module, which comes with Perl, has a C<rmtree> which
1459 can take care of all of the hard work for you:
1461 use File::Path qw(rmtree);
1463 rmtree( \@directories, 0, 0 );
1465 The first argument to C<rmtree> is either a string representing a directory path
1466 or an array reference. The second argument controls progress messages, and the
1467 third argument controls the handling of files you don't have permissions to
1468 delete. See the C<File::Path> module for the details.
1470 =head2 How do I copy an entire directory?
1472 (contributed by Shlomi Fish)
1474 To do the equivalent of C<cp -R> (i.e. copy an entire directory tree
1475 recursively) in portable Perl, you'll either need to write something yourself
1476 or find a good CPAN module such as L<File::Copy::Recursive>.
1479 Revision: $Revision$
1483 See L<perlfaq> for source control details and availability.
1485 =head1 AUTHOR AND COPYRIGHT
1487 Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and
1488 other authors as noted. All rights reserved.
1490 This documentation is free; you can redistribute it and/or modify it
1491 under the same terms as Perl itself.
1493 Irrespective of its distribution, all code examples here are in the public
1494 domain. You are permitted and encouraged to use this code and any
1495 derivatives thereof in your own programs for fun or for profit as you
1496 see fit. A simple comment in the code giving credit to the FAQ would
1497 be courteous but is not required.