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