Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlfaq5.1

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