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