Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1133 lines
39 KiB

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