Leaked source code of windows server 2003
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.

1216 lines
43 KiB

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