1PERLFAQ5(1)            Perl Programmers Reference Guide            PERLFAQ5(1)
2
3
4

NAME

6       perlfaq5 - Files and Formats
7

DESCRIPTION

9       This section deals with I/O and the "f" issues: filehandles, flushing,
10       formats, and footers.
11
12   How do I flush/unbuffer an output filehandle?  Why must I do this?
13       (contributed by brian d foy)
14
15       You might like to read Mark Jason Dominus's "Suffering From Buffering"
16       at http://perl.plover.com/FAQs/Buffering.html .
17
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
20       calls.  For instance, in this little bit of code, you want to print a
21       dot to the screen for every line you process to watch the progress of
22       your program.  Instead of seeing a dot for every line, Perl buffers the
23       output and you have a long wait before you see a row of 50 dots all at
24       once:
25
26               # long wait, then row of dots all at once
27               while( <> ) {
28                       print ".";
29                       print "\n" unless ++$count % 50;
30
31                       #... expensive line processing operations
32                       }
33
34       To get around this, you have to unbuffer the output filehandle, in this
35       case, "STDOUT". You can set the special variable $| to a true value
36       (mnemonic: making your filehandles "piping hot"):
37
38               $|++;
39
40               # dot shown immediately
41               while( <> ) {
42                       print ".";
43                       print "\n" unless ++$count % 50;
44
45                       #... expensive line processing operations
46                       }
47
48       The $| is one of the per-filehandle special variables, so each
49       filehandle has its own copy of its value. If you want to merge standard
50       output and standard error for instance, you have to unbuffer each
51       (although STDERR might be unbuffered by default):
52
53               {
54               my $previous_default = select(STDOUT);  # save previous default
55               $|++;                                   # autoflush STDOUT
56               select(STDERR);
57               $|++;                                   # autoflush STDERR, to be sure
58               select($previous_default);              # restore previous default
59               }
60
61               # now should alternate . and +
62               while( 1 )
63                       {
64                       sleep 1;
65                       print STDOUT ".";
66                       print STDERR "+";
67                       print STDOUT "\n" unless ++$count % 25;
68                       }
69
70       Besides the $| special variable, you can use "binmode" to give your
71       filehandle a ":unix" layer, which is unbuffered:
72
73               binmode( STDOUT, ":unix" );
74
75               while( 1 ) {
76                       sleep 1;
77                       print ".";
78                       print "\n" unless ++$count % 50;
79                       }
80
81       For more information on output layers, see the entries for "binmode"
82       and "open" in perlfunc, and the "PerlIO" module documentation.
83
84       If you are using "IO::Handle" or one of its subclasses, you can call
85       the "autoflush" method to change the settings of the filehandle:
86
87               use IO::Handle;
88               open my( $io_fh ), ">", "output.txt";
89               $io_fh->autoflush(1);
90
91       The "IO::Handle" objects also have a "flush" method. You can flush the
92       buffer any time you want without auto-buffering
93
94               $io_fh->flush;
95
96   How do I change, delete, or insert a line in a file, or append to the
97       beginning of a file?
98       (contributed by brian d foy)
99
100       The basic idea of inserting, changing, or deleting a line from a text
101       file involves reading and printing the file to the point you want to
102       make the change, making the change, then reading and printing the rest
103       of the file. Perl doesn't provide random access to lines (especially
104       since the record input separator, $/, is mutable), although modules
105       such as "Tie::File" can fake it.
106
107       A Perl program to do these tasks takes the basic form of opening a
108       file, printing its lines, then closing the file:
109
110               open my $in,  '<',  $file      or die "Can't read old file: $!";
111               open my $out, '>', "$file.new" or die "Can't write new file: $!";
112
113               while( <$in> )
114                       {
115                       print $out $_;
116                       }
117
118          close $out;
119
120       Within that basic form, add the parts that you need to insert, change,
121       or delete lines.
122
123       To prepend lines to the beginning, print those lines before you enter
124       the loop that prints the existing lines.
125
126               open my $in,  '<',  $file      or die "Can't read old file: $!";
127               open my $out, '>', "$file.new" or die "Can't write new file: $!";
128
129               print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC
130
131               while( <$in> )
132                       {
133                       print $out $_;
134                       }
135
136          close $out;
137
138       To change existing lines, insert the code to modify the lines inside
139       the "while" loop. In this case, the code finds all lowercased versions
140       of "perl" and uppercases them. The happens for every line, so be sure
141       that you're supposed to do that on every line!
142
143               open my $in,  '<',  $file      or die "Can't read old file: $!";
144               open my $out, '>', "$file.new" or die "Can't write new file: $!";
145
146               print $out "# Add this line to the top\n";
147
148               while( <$in> )
149                       {
150                       s/\b(perl)\b/Perl/g;
151                       print $out $_;
152                       }
153
154          close $out;
155
156       To change only a particular line, the input line number, $., is useful.
157       First read and print the lines up to the one you  want to change. Next,
158       read the single line you want to change, change it, and print it. After
159       that, read the rest of the lines and print those:
160
161               while( <$in> )   # print the lines before the change
162                       {
163                       print $out $_;
164                       last if $. == 4; # line number before change
165                       }
166
167               my $line = <$in>;
168               $line =~ s/\b(perl)\b/Perl/g;
169               print $out $line;
170
171               while( <$in> )   # print the rest of the lines
172                       {
173                       print $out $_;
174                       }
175
176       To skip lines, use the looping controls. The "next" in this example
177       skips comment lines, and the "last" stops all processing once it
178       encounters either "__END__" or "__DATA__".
179
180               while( <$in> )
181                       {
182                       next if /^\s+#/;             # skip comment lines
183                       last if /^__(END|DATA)__$/;  # stop at end of code marker
184                       print $out $_;
185                       }
186
187       Do the same sort of thing to delete a particular line by using "next"
188       to skip the lines you don't want to show up in the output. This example
189       skips every fifth line:
190
191               while( <$in> )
192                       {
193                       next unless $. % 5;
194                       print $out $_;
195                       }
196
197       If, for some odd reason, you really want to see the whole file at once
198       rather than processing line-by-line, you can slurp it in (as long as
199       you can fit the whole thing in memory!):
200
201               open my $in,  '<',  $file      or die "Can't read old file: $!"
202               open my $out, '>', "$file.new" or die "Can't write new file: $!";
203
204               my @lines = do { local $/; <$in> }; # slurp!
205
206                       # do your magic here
207
208               print $out @lines;
209
210       Modules such as "File::Slurp" and "Tie::File" can help with that too.
211       If you can, however, avoid reading the entire file at once. Perl won't
212       give that memory back to the operating system until the process
213       finishes.
214
215       You can also use Perl one-liners to modify a file in-place. The
216       following changes all 'Fred' to 'Barney' in inFile.txt, overwriting the
217       file with the new contents. With the "-p" switch, Perl wraps a "while"
218       loop around the code you specify with "-e", and "-i" turns on in-place
219       editing. The current line is in $_. With "-p", Perl automatically
220       prints the value of $_ at the end of the loop. See perlrun for more
221       details.
222
223               perl -pi -e 's/Fred/Barney/' inFile.txt
224
225       To make a backup of "inFile.txt", give "-i" a file extension to add:
226
227               perl -pi.bak -e 's/Fred/Barney/' inFile.txt
228
229       To change only the fifth line, you can add a test checking $., the
230       input line number, then only perform the operation when the test
231       passes:
232
233               perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
234
235       To add lines before a certain line, you can add a line (or lines!)
236       before Perl prints $_:
237
238               perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
239
240       You can even add a line to the beginning of a file, since the current
241       line prints at the end of the loop:
242
243               perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
244
245       To insert a line after one already in the file, use the "-n" switch.
246       It's just like "-p" except that it doesn't print $_ at the end of the
247       loop, so you have to do that yourself. In this case, print $_ first,
248       then print the line that you want to add.
249
250               perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
251
252       To delete lines, only print the ones that you want.
253
254               perl -ni -e 'print unless /d/' inFile.txt
255
256                       ... or ...
257
258               perl -pi -e 'next unless /d/' inFile.txt
259
260   How do I count the number of lines in a file?
261       (contributed by brian d foy)
262
263       Conceptually, the easiest way to count the lines in a file is to simply
264       read them and count them:
265
266               my $count = 0;
267               while( <$fh> ) { $count++; }
268
269       You don't really have to count them yourself, though, since Perl
270       already does that with the $. variable, which is the current line
271       number from the last filehandle read:
272
273               1 while( <$fh> );
274               my $count = $.;
275
276       If you want to use $., you can reduce it to a simple one-liner, like
277       one of these:
278
279               % perl -lne '} print $.; {'    file
280
281               % perl -lne 'END { print $. }' file
282
283       Those can be rather inefficient though. If they aren't fast enough for
284       you, you might just read chunks of data and count the number of
285       newlines:
286
287               my $lines = 0;
288               open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
289               while( sysread $fh, $buffer, 4096 ) {
290                       $lines += ( $buffer =~ tr/\n// );
291                       }
292               close FILE;
293
294       However, that doesn't work if the line ending isn't a newline. You
295       might change that "tr///" to a "s///" so you can count the number of
296       times the input record separator, $/, shows up:
297
298               my $lines = 0;
299               open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
300               while( sysread $fh, $buffer, 4096 ) {
301                       $lines += ( $buffer =~ s|$/||g; );
302                       }
303               close FILE;
304
305       If you don't mind shelling out, the "wc" command is usually the
306       fastest, even with the extra interprocess overhead. Ensure that you
307       have an untainted filename though:
308
309               #!perl -T
310
311               $ENV{PATH} = undef;
312
313               my $lines;
314               if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
315                       $lines = `/usr/bin/wc -l $1`
316                       chomp $lines;
317                       }
318
319   How do I delete the last N lines from a file?
320       (contributed by brian d foy)
321
322       The easiest conceptual solution is to count the lines in the file then
323       start at the beginning and print the number of lines (minus the last N)
324       to a new file.
325
326       Most often, the real question is how you can delete the last N lines
327       without making more than one pass over the file, or how to do it
328       without a lot of copying. The easy concept is the hard reality when you
329       might have millions of lines in your file.
330
331       One trick is to use "File::ReadBackwards", which starts at the end of
332       the file. That module provides an object that wraps the real filehandle
333       to make it easy for you to move around the file. Once you get to the
334       spot you need, you can get the actual filehandle and work with it as
335       normal. In this case, you get the file position at the end of the last
336       line you want to keep and truncate the file to that point:
337
338               use File::ReadBackwards;
339
340               my $filename = 'test.txt';
341               my $Lines_to_truncate = 2;
342
343               my $bw = File::ReadBackwards->new( $filename )
344                       or die "Could not read backwards in [$filename]: $!";
345
346               my $lines_from_end = 0;
347               until( $bw->eof or $lines_from_end == $Lines_to_truncate )
348                       {
349                       print "Got: ", $bw->readline;
350                       $lines_from_end++;
351                       }
352
353               truncate( $filename, $bw->tell );
354
355       The "File::ReadBackwards" module also has the advantage of setting the
356       input record separator to a regular expression.
357
358       You can also use the "Tie::File" module which lets you access the lines
359       through a tied array. You can use normal array operations to modify
360       your file, including setting the last index and using "splice".
361
362   How can I use Perl's "-i" option from within a program?
363       "-i" sets the value of Perl's $^I variable, which in turn affects the
364       behavior of "<>"; see perlrun for more details. By modifying the
365       appropriate variables directly, you can get the same behavior within a
366       larger program. For example:
367
368               # ...
369               {
370               local($^I, @ARGV) = ('.orig', glob("*.c"));
371               while (<>) {
372                       if ($. == 1) {
373                               print "This line should appear at the top of each file\n";
374                       }
375                       s/\b(p)earl\b/${1}erl/i;        # Correct typos, preserving case
376                       print;
377                       close ARGV if eof;              # Reset $.
378                       }
379               }
380               # $^I and @ARGV return to their old values here
381
382       This block modifies all the ".c" files in the current directory,
383       leaving a backup of the original data from each file in a new ".c.orig"
384       file.
385
386   How can I copy a file?
387       (contributed by brian d foy)
388
389       Use the "File::Copy" module. It comes with Perl and can do a true copy
390       across file systems, and it does its magic in a portable fashion.
391
392               use File::Copy;
393
394               copy( $original, $new_copy ) or die "Copy failed: $!";
395
396       If you can't use "File::Copy", you'll have to do the work yourself:
397       open the original file, open the destination file, then print to the
398       destination file as you read the original. You also have to remember to
399       copy the permissions, owner, and group to the new file.
400
401   How do I make a temporary file name?
402       If you don't need to know the name of the file, you can use "open()"
403       with "undef" in place of the file name. In Perl 5.8 or later, the
404       "open()" function creates an anonymous temporary file:
405
406               open my $tmp, '+>', undef or die $!;
407
408       Otherwise, you can use the File::Temp module.
409
410               use File::Temp qw/ tempfile tempdir /;
411
412               my $dir = tempdir( CLEANUP => 1 );
413               ($fh, $filename) = tempfile( DIR => $dir );
414
415               # or if you don't need to know the filename
416
417               my $fh = tempfile( DIR => $dir );
418
419       The File::Temp has been a standard module since Perl 5.6.1. If you
420       don't have a modern enough Perl installed, use the "new_tmpfile" class
421       method from the IO::File module to get a filehandle opened for reading
422       and writing. Use it if you don't need to know the file's name:
423
424               use IO::File;
425               my $fh = IO::File->new_tmpfile()
426                       or die "Unable to make new temporary file: $!";
427
428       If you're committed to creating a temporary file by hand, use the
429       process ID and/or the current time-value. If you need to have many
430       temporary files in one process, use a counter:
431
432               BEGIN {
433               use Fcntl;
434               my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
435               my $base_name = sprintf "%s/%d-%d-0000", $temp_dir, $$, time;
436
437               sub temp_file {
438                       local *FH;
439                       my $count = 0;
440                       until( defined(fileno(FH)) || $count++ > 100 ) {
441                               $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
442                               # O_EXCL is required for security reasons.
443                               sysopen my($fh), $base_name, O_WRONLY|O_EXCL|O_CREAT;
444                               }
445
446                       if( defined fileno($fh) ) {
447                               return ($fh, $base_name);
448                               }
449                       else {
450                               return ();
451                               }
452                       }
453
454               }
455
456   How can I manipulate fixed-record-length files?
457       The most efficient way is using pack() and unpack(). This is faster
458       than using substr() when taking many, many strings. It is slower for
459       just a few.
460
461       Here is a sample chunk of code to break up and put back together again
462       some fixed-format input lines, in this case from the output of a
463       normal, Berkeley-style ps:
464
465               # sample input line:
466               #   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what
467               my $PS_T = 'A6 A4 A7 A5 A*';
468               open my $ps, '-|', 'ps';
469               print scalar <$ps>;
470               my @fields = qw( pid tt stat time command );
471               while (<$ps>) {
472                       my %process;
473                       @process{@fields} = unpack($PS_T, $_);
474               for my $field ( @fields ) {
475                       print "$field: <$process{$field}>\n";
476               }
477               print 'line=', pack($PS_T, @process{@fields} ), "\n";
478               }
479
480       We've used a hash slice in order to easily handle the fields of each
481       row.  Storing the keys in an array means it's easy to operate on them
482       as a group or loop over them with for. It also avoids polluting the
483       program with global variables and using symbolic references.
484
485   How can I make a filehandle local to a subroutine?  How do I pass
486       filehandles between subroutines?  How do I make an array of
487       filehandles?
488       As of perl5.6, open() autovivifies file and directory handles as
489       references if you pass it an uninitialized scalar variable.  You can
490       then pass these references just like any other scalar, and use them in
491       the place of named handles.
492
493               open my    $fh, $file_name;
494
495               open local $fh, $file_name;
496
497               print $fh "Hello World!\n";
498
499               process_file( $fh );
500
501       If you like, you can store these filehandles in an array or a hash.  If
502       you access them directly, they aren't simple scalars and you need to
503       give "print" a little help by placing the filehandle reference in
504       braces. Perl can only figure it out on its own when the filehandle
505       reference is a simple scalar.
506
507               my @fhs = ( $fh1, $fh2, $fh3 );
508
509               for( $i = 0; $i <= $#fhs; $i++ ) {
510                       print {$fhs[$i]} "just another Perl answer, \n";
511                       }
512
513       Before perl5.6, you had to deal with various typeglob idioms which you
514       may see in older code.
515
516               open FILE, "> $filename";
517               process_typeglob(   *FILE );
518               process_reference( \*FILE );
519
520               sub process_typeglob  { local *FH = shift; print FH  "Typeglob!" }
521               sub process_reference { local $fh = shift; print $fh "Reference!" }
522
523       If you want to create many anonymous handles, you should check out the
524       Symbol or IO::Handle modules.
525
526   How can I use a filehandle indirectly?
527       An indirect filehandle is using something other than a symbol in a
528       place that a filehandle is expected. Here are ways to get indirect
529       filehandles:
530
531               $fh =   SOME_FH;       # bareword is strict-subs hostile
532               $fh =  "SOME_FH";      # strict-refs hostile; same package only
533               $fh =  *SOME_FH;       # typeglob
534               $fh = \*SOME_FH;       # ref to typeglob (bless-able)
535               $fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH typeglob
536
537       Or, you can use the "new" method from one of the IO::* modules to
538       create an anonymous filehandle, store that in a scalar variable, and
539       use it as though it were a normal filehandle.
540
541               use IO::Handle;                     # 5.004 or higher
542               my $fh = IO::Handle->new();
543
544       Then use any of those as you would a normal filehandle. Anywhere that
545       Perl is expecting a filehandle, an indirect filehandle may be used
546       instead. An indirect filehandle is just a scalar variable that contains
547       a filehandle. Functions like "print", "open", "seek", or the "<FH>"
548       diamond operator will accept either a named filehandle or a scalar
549       variable containing one:
550
551               ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
552               print $ofh "Type it: ";
553               my $got = <$ifh>
554               print $efh "What was that: $got";
555
556       If you're passing a filehandle to a function, you can write the
557       function in two ways:
558
559               sub accept_fh {
560                       my $fh = shift;
561                       print $fh "Sending to indirect filehandle\n";
562               }
563
564       Or it can localize a typeglob and use the filehandle directly:
565
566               sub accept_fh {
567                       local *FH = shift;
568                       print  FH "Sending to localized filehandle\n";
569               }
570
571       Both styles work with either objects or typeglobs of real filehandles.
572       (They might also work with strings under some circumstances, but this
573       is risky.)
574
575               accept_fh(*STDOUT);
576               accept_fh($handle);
577
578       In the examples above, we assigned the filehandle to a scalar variable
579       before using it. That is because only simple scalar variables, not
580       expressions or subscripts of hashes or arrays, can be used with built-
581       ins like "print", "printf", or the diamond operator. Using something
582       other than a simple scalar variable as a filehandle is illegal and
583       won't even compile:
584
585               my @fd = (*STDIN, *STDOUT, *STDERR);
586               print $fd[1] "Type it: ";                           # WRONG
587               my $got = <$fd[0]>                                  # WRONG
588               print $fd[2] "What was that: $got";                 # WRONG
589
590       With "print" and "printf", you get around this by using a block and an
591       expression where you would place the filehandle:
592
593               print  { $fd[1] } "funny stuff\n";
594               printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
595               # Pity the poor deadbeef.
596
597       That block is a proper block like any other, so you can put more
598       complicated code there. This sends the message out to one of two
599       places:
600
601               my $ok = -x "/bin/cat";
602               print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
603               print { $fd[ 1+ ($ok || 0) ]  } "cat stat $ok\n";
604
605       This approach of treating "print" and "printf" like object methods
606       calls doesn't work for the diamond operator. That's because it's a real
607       operator, not just a function with a comma-less argument. Assuming
608       you've been storing typeglobs in your structure as we did above, you
609       can use the built-in function named "readline" to read a record just as
610       "<>" does. Given the initialization shown above for @fd, this would
611       work, but only because readline() requires a typeglob. It doesn't work
612       with objects or strings, which might be a bug we haven't fixed yet.
613
614               $got = readline($fd[0]);
615
616       Let it be noted that the flakiness of indirect filehandles is not
617       related to whether they're strings, typeglobs, objects, or anything
618       else.  It's the syntax of the fundamental operators. Playing the object
619       game doesn't help you at all here.
620
621   How can I set up a footer format to be used with write()?
622       There's no builtin way to do this, but perlform has a couple of
623       techniques to make it possible for the intrepid hacker.
624
625   How can I write() into a string?
626       See "Accessing Formatting Internals" in perlform for an "swrite()"
627       function.
628
629   How can I open a filehandle to a string?
630       (contributed by Peter J. Holzer, hjp-usenet2@hjp.at)
631
632       Since Perl 5.8.0 a file handle referring to a string can be created by
633       calling open with a reference to that string instead of the filename.
634       This file handle can then be used to read from or write to the string:
635
636               open(my $fh, '>', \$string) or die "Could not open string for writing";
637               print $fh "foo\n";
638               print $fh "bar\n";      # $string now contains "foo\nbar\n"
639
640               open(my $fh, '<', \$string) or die "Could not open string for reading";
641               my $x = <$fh>;  # $x now contains "foo\n"
642
643       With older versions of Perl, the "IO::String" module provides similar
644       functionality.
645
646   How can I output my numbers with commas added?
647       (contributed by brian d foy and Benjamin Goldberg)
648
649       You can use Number::Format to separate places in a number.  It handles
650       locale information for those of you who want to insert full stops
651       instead (or anything else that they want to use, really).
652
653       This subroutine will add commas to your number:
654
655               sub commify {
656                       local $_  = shift;
657                       1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
658                       return $_;
659                       }
660
661       This regex from Benjamin Goldberg will add commas to numbers:
662
663               s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
664
665       It is easier to see with comments:
666
667               s/(
668                       ^[-+]?             # beginning of number.
669                       \d+?               # first digits before first comma
670                       (?=                # followed by, (but not included in the match) :
671                               (?>(?:\d{3})+) # some positive multiple of three digits.
672                               (?!\d)         # an *exact* multiple, not x * 3 + 1 or whatever.
673                       )
674                       |                  # or:
675                       \G\d{3}            # after the last group, get three digits
676                       (?=\d)             # but they have to have more digits after them.
677               )/$1,/xg;
678
679   How can I translate tildes (~) in a filename?
680       Use the <> ("glob()") operator, documented in perlfunc.  Versions of
681       Perl older than 5.6 require that you have a shell installed that groks
682       tildes. Later versions of Perl have this feature built in. The
683       "File::KGlob" module (available from CPAN) gives more portable glob
684       functionality.
685
686       Within Perl, you may use this directly:
687
688               $filename =~ s{
689                 ^ ~             # find a leading tilde
690                 (               # save this in $1
691                     [^/]        # a non-slash character
692                           *     # repeated 0 or more times (0 means me)
693                 )
694               }{
695                 $1
696                     ? (getpwnam($1))[7]
697                     : ( $ENV{HOME} || $ENV{LOGDIR} )
698               }ex;
699
700   How come when I open a file read-write it wipes it out?
701       Because you're using something like this, which truncates the file and
702       then gives you read-write access:
703
704               open my $fh, '+>', '/path/name'; # WRONG (almost always)
705
706       Whoops. You should instead use this, which will fail if the file
707       doesn't exist.
708
709               open my $fh, '+<', '/path/name'; # open for update
710
711       Using ">" always clobbers or creates. Using "<" never does either. The
712       "+" doesn't change this.
713
714       Here are examples of many kinds of file opens. Those using sysopen()
715       all assume
716
717               use Fcntl;
718
719       To open file for reading:
720
721               open my $fh, '<', $path                                 or die $!;
722               sysopen my $fh, $path, O_RDONLY                         or die $!;
723
724       To open file for writing, create new file if needed or else truncate
725       old file:
726
727               open my $fh, '>', $path                                 or die $!;
728               sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT         or die $!;
729               sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666   or die $!;
730
731       To open file for writing, create new file, file must not exist:
732
733               sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT          or die $!;
734               sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT, 0666    or die $!;
735
736       To open file for appending, create if necessary:
737
738               open my $fh, '>>' $path                                 or die $!;
739               sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT        or die $!;
740               sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT, 0666  or die $!;
741
742       To open file for appending, file must exist:
743
744               sysopen my $fh, $path, O_WRONLY|O_APPEND                or die $!;
745
746       To open file for update, file must exist:
747
748               open my $fh, '+<', $path                                or die $!;
749               sysopen my $fh, $path, O_RDWR                           or die $!;
750
751       To open file for update, create file if necessary:
752
753               sysopen my $fh, $path, O_RDWR|O_CREAT                   or die $!;
754               sysopen my $fh, $path, O_RDWR|O_CREAT, 0666             or die $!;
755
756       To open file for update, file must not exist:
757
758               sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT            or die $!;
759               sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT, 0666      or die $!;
760
761       To open a file without blocking, creating if necessary:
762
763               sysopen my $fh, '/foo/somefile', O_WRONLY|O_NDELAY|O_CREAT
764                   or die "can't open /foo/somefile: $!":
765
766       Be warned that neither creation nor deletion of files is guaranteed to
767       be an atomic operation over NFS. That is, two processes might both
768       successfully create or unlink the same file! Therefore O_EXCL isn't as
769       exclusive as you might wish.
770
771       See also the new perlopentut.
772
773   Why do I sometimes get an "Argument list too long" when I use <*>?
774       The "<>" operator performs a globbing operation (see above).  In Perl
775       versions earlier than v5.6.0, the internal glob() operator forks csh(1)
776       to do the actual glob expansion, but csh can't handle more than 127
777       items and so gives the error message "Argument list too long". People
778       who installed tcsh as csh won't have this problem, but their users may
779       be surprised by it.
780
781       To get around this, either upgrade to Perl v5.6.0 or later, do the glob
782       yourself with readdir() and patterns, or use a module like File::KGlob,
783       one that doesn't use the shell to do globbing.
784
785   Is there a leak/bug in glob()?
786       (contributed by brian d foy)
787
788       Starting with Perl 5.6.0, "glob" is implemented internally rather than
789       relying on an external resource. As such, memory issues with "glob"
790       aren't a problem in modern perls.
791
792   How can I open a file with a leading ">" or trailing blanks?
793       (contributed by Brian McCauley)
794
795       The special two argument form of Perl's open() function ignores
796       trailing blanks in filenames and infers the mode from certain leading
797       characters (or a trailing "|"). In older versions of Perl this was the
798       only version of open() and so it is prevalent in old code and books.
799
800       Unless you have a particular reason to use the two argument form you
801       should use the three argument form of open() which does not treat any
802       characters in the filename as special.
803
804               open my $fh, "<", "  file  ";  # filename is "   file   "
805               open my $fh, ">", ">file";     # filename is ">file"
806
807   How can I reliably rename a file?
808       If your operating system supports a proper mv(1) utility or its
809       functional equivalent, this works:
810
811               rename($old, $new) or system("mv", $old, $new);
812
813       It may be more portable to use the "File::Copy" module instead.  You
814       just copy to the new file to the new name (checking return values),
815       then delete the old one. This isn't really the same semantically as a
816       "rename()", which preserves meta-information like permissions,
817       timestamps, inode info, etc.
818
819   How can I lock a file?
820       Perl's builtin flock() function (see perlfunc for details) will call
821       flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004
822       and later), and lockf(3) if neither of the two previous system calls
823       exists.  On some systems, it may even use a different form of native
824       locking.  Here are some gotchas with Perl's flock():
825
826       1.  Produces a fatal error if none of the three system calls (or their
827           close equivalent) exists.
828
829       2.  lockf(3) does not provide shared locking, and requires that the
830           filehandle be open for writing (or appending, or read/writing).
831
832       3.  Some versions of flock() can't lock files over a network (e.g. on
833           NFS file systems), so you'd need to force the use of fcntl(2) when
834           you build Perl.  But even this is dubious at best. See the flock
835           entry of perlfunc and the INSTALL file in the source distribution
836           for information on building Perl to do this.
837
838           Two potentially non-obvious but traditional flock semantics are
839           that it waits indefinitely until the lock is granted, and that its
840           locks are merely advisory. Such discretionary locks are more
841           flexible, but offer fewer guarantees. This means that files locked
842           with flock() may be modified by programs that do not also use
843           flock(). Cars that stop for red lights get on well with each other,
844           but not with cars that don't stop for red lights. See the perlport
845           manpage, your port's specific documentation, or your system-
846           specific local manpages for details. It's best to assume
847           traditional behavior if you're writing portable programs.  (If
848           you're not, you should as always feel perfectly free to write for
849           your own system's idiosyncrasies (sometimes called "features").
850           Slavish adherence to portability concerns shouldn't get in the way
851           of your getting your job done.)
852
853           For more information on file locking, see also "File Locking" in
854           perlopentut if you have it (new for 5.6).
855
856   Why can't I just open(FH, ">file.lock")?
857       A common bit of code NOT TO USE is this:
858
859               sleep(3) while -e 'file.lock';  # PLEASE DO NOT USE
860               open my $lock, '>', 'file.lock'; # THIS BROKEN CODE
861
862       This is a classic race condition: you take two steps to do something
863       which must be done in one. That's why computer hardware provides an
864       atomic test-and-set instruction. In theory, this "ought" to work:
865
866               sysopen my $fh, "file.lock", O_WRONLY|O_EXCL|O_CREAT
867                       or die "can't open  file.lock: $!";
868
869       except that lamentably, file creation (and deletion) is not atomic over
870       NFS, so this won't work (at least, not every time) over the net.
871       Various schemes involving link() have been suggested, but these tend to
872       involve busy-wait, which is also less than desirable.
873
874   I still don't get locking. I just want to increment the number in the file.
875       How can I do this?
876       Didn't anyone ever tell you web-page hit counters were useless?  They
877       don't count number of hits, they're a waste of time, and they serve
878       only to stroke the writer's vanity. It's better to pick a random
879       number; they're more realistic.
880
881       Anyway, this is what you can do if you can't help yourself.
882
883               use Fcntl qw(:DEFAULT :flock);
884               sysopen my $fh, "numfile", O_RDWR|O_CREAT or die "can't open numfile: $!";
885               flock $fh, LOCK_EX                        or die "can't flock numfile: $!";
886               my $num = <$fh> || 0;
887               seek $fh, 0, 0                            or die "can't rewind numfile: $!";
888               truncate $fh, 0                           or die "can't truncate numfile: $!";
889               (print $fh $num+1, "\n")                  or die "can't write numfile: $!";
890               close $fh                                 or die "can't close numfile: $!";
891
892       Here's a much better web-page hit counter:
893
894               $hits = int( (time() - 850_000_000) / rand(1_000) );
895
896       If the count doesn't impress your friends, then the code might. :-)
897
898   All I want to do is append a small amount of text to the end of a file. Do
899       I still have to use locking?
900       If you are on a system that correctly implements "flock" and you use
901       the example appending code from "perldoc -f flock" everything will be
902       OK even if the OS you are on doesn't implement append mode correctly
903       (if such a system exists.) So if you are happy to restrict yourself to
904       OSs that implement "flock" (and that's not really much of a
905       restriction) then that is what you should do.
906
907       If you know you are only going to use a system that does correctly
908       implement appending (i.e. not Win32) then you can omit the "seek" from
909       the code in the previous answer.
910
911       If you know you are only writing code to run on an OS and filesystem
912       that does implement append mode correctly (a local filesystem on a
913       modern Unix for example), and you keep the file in block-buffered mode
914       and you write less than one buffer-full of output between each manual
915       flushing of the buffer then each bufferload is almost guaranteed to be
916       written to the end of the file in one chunk without getting
917       intermingled with anyone else's output. You can also use the "syswrite"
918       function which is simply a wrapper around your system's write(2) system
919       call.
920
921       There is still a small theoretical chance that a signal will interrupt
922       the system level "write()" operation before completion. There is also a
923       possibility that some STDIO implementations may call multiple system
924       level "write()"s even if the buffer was empty to start. There may be
925       some systems where this probability is reduced to zero, and this is not
926       a concern when using ":perlio" instead of your system's STDIO.
927
928   How do I randomly update a binary file?
929       If you're just trying to patch a binary, in many cases something as
930       simple as this works:
931
932               perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
933
934       However, if you have fixed sized records, then you might do something
935       more like this:
936
937               $RECSIZE = 220; # size of record, in bytes
938               $recno   = 37;  # which record to update
939               open my $fh, '+<', 'somewhere' or die "can't update somewhere: $!";
940               seek $fh, $recno * $RECSIZE, 0;
941               read $fh, $record, $RECSIZE == $RECSIZE or die "can't read record $recno: $!";
942               # munge the record
943               seek $fh, -$RECSIZE, 1;
944               print $fh $record;
945               close $fh;
946
947       Locking and error checking are left as an exercise for the reader.
948       Don't forget them or you'll be quite sorry.
949
950   How do I get a file's timestamp in perl?
951       If you want to retrieve the time at which the file was last read,
952       written, or had its meta-data (owner, etc) changed, you use the -A, -M,
953       or -C file test operations as documented in perlfunc.  These retrieve
954       the age of the file (measured against the start-time of your program)
955       in days as a floating point number. Some platforms may not have all of
956       these times. See perlport for details. To retrieve the "raw" time in
957       seconds since the epoch, you would call the stat function, then use
958       "localtime()", "gmtime()", or "POSIX::strftime()" to convert this into
959       human-readable form.
960
961       Here's an example:
962
963               my $write_secs = (stat($file))[9];
964               printf "file %s updated at %s\n", $file,
965               scalar localtime($write_secs);
966
967       If you prefer something more legible, use the File::stat module (part
968       of the standard distribution in version 5.004 and later):
969
970               # error checking left as an exercise for reader.
971               use File::stat;
972               use Time::localtime;
973               my $date_string = ctime(stat($file)->mtime);
974               print "file $file updated at $date_string\n";
975
976       The POSIX::strftime() approach has the benefit of being, in theory,
977       independent of the current locale. See perllocale for details.
978
979   How do I set a file's timestamp in perl?
980       You use the utime() function documented in "utime" in perlfunc.  By way
981       of example, here's a little program that copies the read and write
982       times from its first argument to all the rest of them.
983
984               if (@ARGV < 2) {
985                       die "usage: cptimes timestamp_file other_files ...\n";
986                       }
987               my $timestamp = shift;
988               my($atime, $mtime) = (stat($timestamp))[8,9];
989               utime $atime, $mtime, @ARGV;
990
991       Error checking is, as usual, left as an exercise for the reader.
992
993       The perldoc for utime also has an example that has the same effect as
994       touch(1) on files that already exist.
995
996       Certain file systems have a limited ability to store the times on a
997       file at the expected level of precision. For example, the FAT and HPFS
998       filesystem are unable to create dates on files with a finer granularity
999       than two seconds. This is a limitation of the filesystems, not of
1000       utime().
1001
1002   How do I print to more than one file at once?
1003       To connect one filehandle to several output filehandles, you can use
1004       the IO::Tee or Tie::FileHandle::Multiplex modules.
1005
1006       If you only have to do this once, you can print individually to each
1007       filehandle.
1008
1009               for my $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
1010
1011   How can I read in an entire file all at once?
1012       Are you sure you want to read the entire file and store it in memory?
1013       If you mmap the file, you can virtually load the entire file into a
1014       string without actually storing it in memory:
1015
1016               use File::Map qw(map_file);
1017
1018               map_file my $string, $filename;
1019
1020       Once mapped, you can treat $string as you would any other string.
1021       Since you don't actually load the data, mmap-ing is very fast and does
1022       not increase your memory footprint.
1023
1024       If you really want to load the entire file, you can use the
1025       "File::Slurp" module to do it in one step.
1026
1027               use File::Slurp;
1028
1029               my $all_of_it = read_file($filename); # entire file in scalar
1030               my @all_lines = read_file($filename); # one line per element
1031
1032       The customary Perl approach for processing all the lines in a file is
1033       to do so one line at a time:
1034
1035               open my $input, '<', $file or die "can't open $file: $!";
1036               while (<$input>) {
1037                       chomp;
1038                       # do something with $_
1039                       }
1040               close $input or die "can't close $file: $!";
1041
1042       This is tremendously more efficient than reading the entire file into
1043       memory as an array of lines and then processing it one element at a
1044       time, which is often--if not almost always--the wrong approach.
1045       Whenever you see someone do this:
1046
1047               my @lines = <INPUT>;
1048
1049       You should think long and hard about why you need everything loaded at
1050       once. It's just not a scalable solution. You might also find it more
1051       fun to use the standard Tie::File module, or the DB_File module's
1052       $DB_RECNO bindings, which allow you to tie an array to a file so that
1053       accessing an element the array actually accesses the corresponding line
1054       in the file.
1055
1056       You can read the entire filehandle contents into a scalar.
1057
1058               {
1059               local $/;
1060               open my $fh, '<', $file or die "can't open $file: $!";
1061               $var = <$fh>;
1062               }
1063
1064       That temporarily undefs your record separator, and will automatically
1065       close the file at block exit. If the file is already open, just use
1066       this:
1067
1068               $var = do { local $/; <$fh> };
1069
1070       For ordinary files you can also use the read function.
1071
1072               read( $fh, $var, -s $fh );
1073
1074       The third argument tests the byte size of the data on the INPUT
1075       filehandle and reads that many bytes into the buffer $var.
1076
1077   How can I read in a file by paragraphs?
1078       Use the $/ variable (see perlvar for details). You can either set it to
1079       "" to eliminate empty paragraphs ("abc\n\n\n\ndef", for instance, gets
1080       treated as two paragraphs and not three), or "\n\n" to accept empty
1081       paragraphs.
1082
1083       Note that a blank line must have no blanks in it. Thus
1084       "fred\n \nstuff\n\n" is one paragraph, but "fred\n\nstuff\n\n" is two.
1085
1086   How can I read a single character from a file?  From the keyboard?
1087       You can use the builtin "getc()" function for most filehandles, but it
1088       won't (easily) work on a terminal device. For STDIN, either use the
1089       Term::ReadKey module from CPAN or use the sample code in "getc" in
1090       perlfunc.
1091
1092       If your system supports the portable operating system programming
1093       interface (POSIX), you can use the following code, which you'll note
1094       turns off echo processing as well.
1095
1096               #!/usr/bin/perl -w
1097               use strict;
1098               $| = 1;
1099               for (1..4) {
1100                       print "gimme: ";
1101                       my $got = getone();
1102                       print "--> $got\n";
1103                       }
1104           exit;
1105
1106               BEGIN {
1107               use POSIX qw(:termios_h);
1108
1109               my ($term, $oterm, $echo, $noecho, $fd_stdin);
1110
1111               my $fd_stdin = fileno(STDIN);
1112
1113               $term     = POSIX::Termios->new();
1114               $term->getattr($fd_stdin);
1115               $oterm     = $term->getlflag();
1116
1117               $echo     = ECHO | ECHOK | ICANON;
1118               $noecho   = $oterm & ~$echo;
1119
1120               sub cbreak {
1121                       $term->setlflag($noecho);
1122                       $term->setcc(VTIME, 1);
1123                       $term->setattr($fd_stdin, TCSANOW);
1124                       }
1125
1126               sub cooked {
1127                       $term->setlflag($oterm);
1128                       $term->setcc(VTIME, 0);
1129                       $term->setattr($fd_stdin, TCSANOW);
1130                       }
1131
1132               sub getone {
1133                       my $key = '';
1134                       cbreak();
1135                       sysread(STDIN, $key, 1);
1136                       cooked();
1137                       return $key;
1138                       }
1139
1140               }
1141
1142               END { cooked() }
1143
1144       The Term::ReadKey module from CPAN may be easier to use. Recent
1145       versions include also support for non-portable systems as well.
1146
1147               use Term::ReadKey;
1148               open my $tty, '<', '/dev/tty';
1149               print "Gimme a char: ";
1150               ReadMode "raw";
1151               my $key = ReadKey 0, $tty;
1152               ReadMode "normal";
1153               printf "\nYou said %s, char number %03d\n",
1154                       $key, ord $key;
1155
1156   How can I tell whether there's a character waiting on a filehandle?
1157       The very first thing you should do is look into getting the
1158       Term::ReadKey extension from CPAN. As we mentioned earlier, it now even
1159       has limited support for non-portable (read: not open systems, closed,
1160       proprietary, not POSIX, not Unix, etc.) systems.
1161
1162       You should also check out the Frequently Asked Questions list in
1163       comp.unix.* for things like this: the answer is essentially the same.
1164       It's very system dependent. Here's one solution that works on BSD
1165       systems:
1166
1167               sub key_ready {
1168                       my($rin, $nfd);
1169                       vec($rin, fileno(STDIN), 1) = 1;
1170                       return $nfd = select($rin,undef,undef,0);
1171                       }
1172
1173       If you want to find out how many characters are waiting, there's also
1174       the FIONREAD ioctl call to be looked at. The h2ph tool that comes with
1175       Perl tries to convert C include files to Perl code, which can be
1176       "require"d. FIONREAD ends up defined as a function in the sys/ioctl.ph
1177       file:
1178
1179               require 'sys/ioctl.ph';
1180
1181               $size = pack("L", 0);
1182               ioctl(FH, FIONREAD(), $size)    or die "Couldn't call ioctl: $!\n";
1183               $size = unpack("L", $size);
1184
1185       If h2ph wasn't installed or doesn't work for you, you can grep the
1186       include files by hand:
1187
1188               % grep FIONREAD /usr/include/*/*
1189               /usr/include/asm/ioctls.h:#define FIONREAD      0x541B
1190
1191       Or write a small C program using the editor of champions:
1192
1193               % cat > fionread.c
1194               #include <sys/ioctl.h>
1195               main() {
1196                   printf("%#08x\n", FIONREAD);
1197               }
1198               ^D
1199               % cc -o fionread fionread.c
1200               % ./fionread
1201               0x4004667f
1202
1203       And then hard code it, leaving porting as an exercise to your
1204       successor.
1205
1206               $FIONREAD = 0x4004667f;         # XXX: opsys dependent
1207
1208               $size = pack("L", 0);
1209               ioctl(FH, $FIONREAD, $size)     or die "Couldn't call ioctl: $!\n";
1210               $size = unpack("L", $size);
1211
1212       FIONREAD requires a filehandle connected to a stream, meaning that
1213       sockets, pipes, and tty devices work, but not files.
1214
1215   How do I do a "tail -f" in perl?
1216       First try
1217
1218               seek(GWFILE, 0, 1);
1219
1220       The statement "seek(GWFILE, 0, 1)" doesn't change the current position,
1221       but it does clear the end-of-file condition on the handle, so that the
1222       next "<GWFILE>" makes Perl try again to read something.
1223
1224       If that doesn't work (it relies on features of your stdio
1225       implementation), then you need something more like this:
1226
1227               for (;;) {
1228                 for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) {
1229                   # search for some stuff and put it into files
1230                 }
1231                 # sleep for a while
1232                 seek(GWFILE, $curpos, 0);  # seek to where we had been
1233               }
1234
1235       If this still doesn't work, look into the "clearerr" method from
1236       "IO::Handle", which resets the error and end-of-file states on the
1237       handle.
1238
1239       There's also a "File::Tail" module from CPAN.
1240
1241   How do I dup() a filehandle in Perl?
1242       If you check "open" in perlfunc, you'll see that several of the ways to
1243       call open() should do the trick. For example:
1244
1245               open my $log, '>>', '/foo/logfile';
1246               open STDERR, '>&LOG';
1247
1248       Or even with a literal numeric descriptor:
1249
1250               my $fd = $ENV{MHCONTEXTFD};
1251               open $mhcontext, "<&=$fd";  # like fdopen(3S)
1252
1253       Note that "<&STDIN" makes a copy, but "<&=STDIN" make an alias. That
1254       means if you close an aliased handle, all aliases become inaccessible.
1255       This is not true with a copied one.
1256
1257       Error checking, as always, has been left as an exercise for the reader.
1258
1259   How do I close a file descriptor by number?
1260       If, for some reason, you have a file descriptor instead of a filehandle
1261       (perhaps you used "POSIX::open"), you can use the "close()" function
1262       from the "POSIX" module:
1263
1264               use POSIX ();
1265
1266               POSIX::close( $fd );
1267
1268       This should rarely be necessary, as the Perl "close()" function is to
1269       be used for things that Perl opened itself, even if it was a dup of a
1270       numeric descriptor as with "MHCONTEXT" above. But if you really have
1271       to, you may be able to do this:
1272
1273               require 'sys/syscall.ph';
1274               my $rc = syscall(&SYS_close, $fd + 0);  # must force numeric
1275               die "can't sysclose $fd: $!" unless $rc == -1;
1276
1277       Or, just use the fdopen(3S) feature of "open()":
1278
1279               {
1280               open my( $fh ), "<&=$fd" or die "Cannot reopen fd=$fd: $!";
1281               close $fh;
1282               }
1283
1284   Why can't I use "C:\temp\foo" in DOS paths?  Why doesn't `C:\temp\foo.exe`
1285       work?
1286       Whoops!  You just put a tab and a formfeed into that filename!
1287       Remember that within double quoted strings ("like\this"), the backslash
1288       is an escape character. The full list of these is in "Quote and Quote-
1289       like Operators" in perlop. Unsurprisingly, you don't have a file called
1290       "c:(tab)emp(formfeed)oo" or "c:(tab)emp(formfeed)oo.exe" on your legacy
1291       DOS filesystem.
1292
1293       Either single-quote your strings, or (preferably) use forward slashes.
1294       Since all DOS and Windows versions since something like MS-DOS 2.0 or
1295       so have treated "/" and "\" the same in a path, you might as well use
1296       the one that doesn't clash with Perl--or the POSIX shell, ANSI C and
1297       C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are
1298       more portable, too.
1299
1300   Why doesn't glob("*.*") get all the files?
1301       Because even on non-Unix ports, Perl's glob function follows standard
1302       Unix globbing semantics. You'll need "glob("*")" to get all (non-
1303       hidden) files. This makes glob() portable even to legacy systems. Your
1304       port may include proprietary globbing functions as well. Check its
1305       documentation for details.
1306
1307   Why does Perl let me delete read-only files?  Why does "-i" clobber
1308       protected files?  Isn't this a bug in Perl?
1309       This is elaborately and painstakingly described in the file-dir-perms
1310       article in the "Far More Than You Ever Wanted To Know" collection in
1311       http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .
1312
1313       The executive summary: learn how your filesystem works. The permissions
1314       on a file say what can happen to the data in that file.  The
1315       permissions on a directory say what can happen to the list of files in
1316       that directory. If you delete a file, you're removing its name from the
1317       directory (so the operation depends on the permissions of the
1318       directory, not of the file). If you try to write to the file, the
1319       permissions of the file govern whether you're allowed to.
1320
1321   How do I select a random line from a file?
1322       Short of loading the file into a database or pre-indexing the lines in
1323       the file, there are a couple of things that you can do.
1324
1325       Here's a reservoir-sampling algorithm from the Camel Book:
1326
1327               srand;
1328               rand($.) < 1 && ($line = $_) while <>;
1329
1330       This has a significant advantage in space over reading the whole file
1331       in. You can find a proof of this method in The Art of Computer
1332       Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
1333
1334       You can use the "File::Random" module which provides a function for
1335       that algorithm:
1336
1337               use File::Random qw/random_line/;
1338               my $line = random_line($filename);
1339
1340       Another way is to use the "Tie::File" module, which treats the entire
1341       file as an array. Simply access a random array element.
1342
1343   Why do I get weird spaces when I print an array of lines?
1344       (contributed by brian d foy)
1345
1346       If you are seeing spaces between the elements of your array when you
1347       print the array, you are probably interpolating the array in double
1348       quotes:
1349
1350               my @animals = qw(camel llama alpaca vicuna);
1351               print "animals are: @animals\n";
1352
1353       It's the double quotes, not the "print", doing this. Whenever you
1354       interpolate an array in a double quote context, Perl joins the elements
1355       with spaces (or whatever is in $", which is a space by default):
1356
1357               animals are: camel llama alpaca vicuna
1358
1359       This is different than printing the array without the interpolation:
1360
1361               my @animals = qw(camel llama alpaca vicuna);
1362               print "animals are: ", @animals, "\n";
1363
1364       Now the output doesn't have the spaces between the elements because the
1365       elements of @animals simply become part of the list to "print":
1366
1367               animals are: camelllamaalpacavicuna
1368
1369       You might notice this when each of the elements of @array end with a
1370       newline. You expect to print one element per line, but notice that
1371       every line after the first is indented:
1372
1373               this is a line
1374                this is another line
1375                this is the third line
1376
1377       That extra space comes from the interpolation of the array. If you
1378       don't want to put anything between your array elements, don't use the
1379       array in double quotes. You can send it to print without them:
1380
1381               print @lines;
1382
1383   How do I traverse a directory tree?
1384       (contributed by brian d foy)
1385
1386       The "File::Find" module, which comes with Perl, does all of the hard
1387       work to traverse a directory structure. It comes with Perl. You simply
1388       call the "find" subroutine with a callback subroutine and the
1389       directories you want to traverse:
1390
1391               use File::Find;
1392
1393               find( \&wanted, @directories );
1394
1395               sub wanted {
1396                       # full path in $File::Find::name
1397                       # just filename in $_
1398                       ... do whatever you want to do ...
1399                       }
1400
1401       The "File::Find::Closures", which you can download from CPAN, provides
1402       many ready-to-use subroutines that you can use with "File::Find".
1403
1404       The "File::Finder", which you can download from CPAN, can help you
1405       create the callback subroutine using something closer to the syntax of
1406       the "find" command-line utility:
1407
1408               use File::Find;
1409               use File::Finder;
1410
1411               my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');
1412
1413               find( $deep_dirs->as_options, @places );
1414
1415       The "File::Find::Rule" module, which you can download from CPAN, has a
1416       similar interface, but does the traversal for you too:
1417
1418               use File::Find::Rule;
1419
1420               my @files = File::Find::Rule->file()
1421                                                                ->name( '*.pm' )
1422                                                                ->in( @INC );
1423
1424   How do I delete a directory tree?
1425       (contributed by brian d foy)
1426
1427       If you have an empty directory, you can use Perl's built-in "rmdir".
1428       If the directory is not empty (so, no files or subdirectories), you
1429       either have to empty it yourself (a lot of work) or use a module to
1430       help you.
1431
1432       The "File::Path" module, which comes with Perl, has a "remove_tree"
1433       which can take care of all of the hard work for you:
1434
1435               use File::Path qw(remove_tree);
1436
1437               remove_tree( @directories );
1438
1439       The "File::Path" module also has a legacy interface to the older
1440       "rmtree" subroutine.
1441
1442   How do I copy an entire directory?
1443       (contributed by Shlomi Fish)
1444
1445       To do the equivalent of "cp -R" (i.e. copy an entire directory tree
1446       recursively) in portable Perl, you'll either need to write something
1447       yourself or find a good CPAN module such as  File::Copy::Recursive.
1448
1450       Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1451       authors as noted. All rights reserved.
1452
1453       This documentation is free; you can redistribute it and/or modify it
1454       under the same terms as Perl itself.
1455
1456       Irrespective of its distribution, all code examples here are in the
1457       public domain. You are permitted and encouraged to use this code and
1458       any derivatives thereof in your own programs for fun or for profit as
1459       you see fit. A simple comment in the code giving credit to the FAQ
1460       would be courteous but is not required.
1461
1462
1463
1464perl v5.12.4                      2011-06-07                       PERLFAQ5(1)
Impressum