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