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