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.

862 lines
33 KiB

  1. =head1 NAME
  2. perlopentut - tutorial on opening things in Perl
  3. =head1 DESCRIPTION
  4. Perl has two simple, built-in ways to open files: the shell way for
  5. convenience, and the C way for precision. The choice is yours.
  6. =head1 Open E<agrave> la shell
  7. Perl's C<open> function was designed to mimic the way command-line
  8. redirection in the shell works. Here are some basic examples
  9. from the shell:
  10. $ myprogram file1 file2 file3
  11. $ myprogram < inputfile
  12. $ myprogram > outputfile
  13. $ myprogram >> outputfile
  14. $ myprogram | otherprogram
  15. $ otherprogram | myprogram
  16. And here are some more advanced examples:
  17. $ otherprogram | myprogram f1 - f2
  18. $ otherprogram 2>&1 | myprogram -
  19. $ myprogram <&3
  20. $ myprogram >&4
  21. Programmers accustomed to constructs like those above can take comfort
  22. in learning that Perl directly supports these familiar constructs using
  23. virtually the same syntax as the shell.
  24. =head2 Simple Opens
  25. The C<open> function takes two arguments: the first is a filehandle,
  26. and the second is a single string comprising both what to open and how
  27. to open it. C<open> returns true when it works, and when it fails,
  28. returns a false value and sets the special variable $! to reflect
  29. the system error. If the filehandle was previously opened, it will
  30. be implicitly closed first.
  31. For example:
  32. open(INFO, "datafile") || die("can't open datafile: $!");
  33. open(INFO, "< datafile") || die("can't open datafile: $!");
  34. open(RESULTS,"> runstats") || die("can't open runstats: $!");
  35. open(LOG, ">> logfile ") || die("can't open logfile: $!");
  36. If you prefer the low-punctuation version, you could write that this way:
  37. open INFO, "< datafile" or die "can't open datafile: $!";
  38. open RESULTS,"> runstats" or die "can't open runstats: $!";
  39. open LOG, ">> logfile " or die "can't open logfile: $!";
  40. A few things to notice. First, the leading less-than is optional.
  41. If omitted, Perl assumes that you want to open the file for reading.
  42. The other important thing to notice is that, just as in the shell,
  43. any white space before or after the filename is ignored. This is good,
  44. because you wouldn't want these to do different things:
  45. open INFO, "<datafile"
  46. open INFO, "< datafile"
  47. open INFO, "< datafile"
  48. Ignoring surround whitespace also helps for when you read a filename in
  49. from a different file, and forget to trim it before opening:
  50. $filename = <INFO>; # oops, \n still there
  51. open(EXTRA, "< $filename") || die "can't open $filename: $!";
  52. This is not a bug, but a feature. Because C<open> mimics the shell in
  53. its style of using redirection arrows to specify how to open the file, it
  54. also does so with respect to extra white space around the filename itself
  55. as well. For accessing files with naughty names, see L</"Dispelling
  56. the Dweomer">.
  57. =head2 Pipe Opens
  58. In C, when you want to open a file using the standard I/O library,
  59. you use the C<fopen> function, but when opening a pipe, you use the
  60. C<popen> function. But in the shell, you just use a different redirection
  61. character. That's also the case for Perl. The C<open> call
  62. remains the same--just its argument differs.
  63. If the leading character is a pipe symbol, C<open) starts up a new
  64. command and open a write-only filehandle leading into that command.
  65. This lets you write into that handle and have what you write show up on
  66. that command's standard input. For example:
  67. open(PRINTER, "| lpr -Plp1") || die "cannot fork: $!";
  68. print PRINTER "stuff\n";
  69. close(PRINTER) || die "can't close lpr: $!";
  70. If the trailing character is a pipe, you start up a new command and open a
  71. read-only filehandle leading out of that command. This lets whatever that
  72. command writes to its standard output show up on your handle for reading.
  73. For example:
  74. open(NET, "netstat -i -n |") || die "cannot fork: $!";
  75. while (<NET>) { } # do something with input
  76. close(NET) || die "can't close netstat: $!";
  77. What happens if you try to open a pipe to or from a non-existent command?
  78. In most systems, such an C<open> will not return an error. That's
  79. because in the traditional C<fork>/C<exec> model, running the other
  80. program happens only in the forked child process, which means that
  81. the failed C<exec> can't be reflected in the return value of C<open>.
  82. Only a failed C<fork> shows up there. See L<perlfaq8/"Why doesn't open()
  83. return an error when a pipe open fails?"> to see how to cope with this.
  84. There's also an explanation in L<perlipc>.
  85. If you would like to open a bidirectional pipe, the IPC::Open2
  86. library will handle this for you. Check out L<perlipc/"Bidirectional
  87. Communication with Another Process">
  88. =head2 The Minus File
  89. Again following the lead of the standard shell utilities, Perl's
  90. C<open> function treats a file whose name is a single minus, "-", in a
  91. special way. If you open minus for reading, it really means to access
  92. the standard input. If you open minus for writing, it really means to
  93. access the standard output.
  94. If minus can be used as the default input or default output? What happens
  95. if you open a pipe into or out of minus? What's the default command it
  96. would run? The same script as you're current running! This is actually
  97. a stealth C<fork> hidden inside an C<open> call. See L<perlipc/"Safe Pipe
  98. Opens"> for details.
  99. =head2 Mixing Reads and Writes
  100. It is possible to specify both read and write access. All you do is
  101. add a "+" symbol in front of the redirection. But as in the shell,
  102. using a less-than on a file never creates a new file; it only opens an
  103. existing one. On the other hand, using a greater-than always clobbers
  104. (truncates to zero length) an existing file, or creates a brand-new one
  105. if there isn't an old one. Adding a "+" for read-write doesn't affect
  106. whether it only works on existing files or always clobbers existing ones.
  107. open(WTMP, "+< /usr/adm/wtmp")
  108. || die "can't open /usr/adm/wtmp: $!";
  109. open(SCREEN, "+> /tmp/lkscreen")
  110. || die "can't open /tmp/lkscreen: $!";
  111. open(LOGFILE, "+>> /tmp/applog"
  112. || die "can't open /tmp/applog: $!";
  113. The first one won't create a new file, and the second one will always
  114. clobber an old one. The third one will create a new file if necessary
  115. and not clobber an old one, and it will allow you to read at any point
  116. in the file, but all writes will always go to the end. In short,
  117. the first case is substantially more common than the second and third
  118. cases, which are almost always wrong. (If you know C, the plus in
  119. Perl's C<open> is historically derived from the one in C's fopen(3S),
  120. which it ultimately calls.)
  121. In fact, when it comes to updating a file, unless you're working on
  122. a binary file as in the WTMP case above, you probably don't want to
  123. use this approach for updating. Instead, Perl's B<-i> flag comes to
  124. the rescue. The following command takes all the C, C++, or yacc source
  125. or header files and changes all their foo's to bar's, leaving
  126. the old version in the original file name with a ".orig" tacked
  127. on the end:
  128. $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]
  129. This is a short cut for some renaming games that are really
  130. the best way to update textfiles. See the second question in
  131. L<perlfaq5> for more details.
  132. =head2 Filters
  133. One of the most common uses for C<open> is one you never
  134. even notice. When you process the ARGV filehandle using
  135. C<E<lt>ARGVE<gt>>, Perl actually does an implicit open
  136. on each file in @ARGV. Thus a program called like this:
  137. $ myprogram file1 file2 file3
  138. Can have all its files opened and processed one at a time
  139. using a construct no more complex than:
  140. while (<>) {
  141. # do something with $_
  142. }
  143. If @ARGV is empty when the loop first begins, Perl pretends you've opened
  144. up minus, that is, the standard input. In fact, $ARGV, the currently
  145. open file during C<E<lt>ARGVE<gt>> processing, is even set to "-"
  146. in these circumstances.
  147. You are welcome to pre-process your @ARGV before starting the loop to
  148. make sure it's to your liking. One reason to do this might be to remove
  149. command options beginning with a minus. While you can always roll the
  150. simple ones by hand, the Getopts modules are good for this.
  151. use Getopt::Std;
  152. # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o
  153. getopts("vDo:");
  154. # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
  155. getopts("vDo:", \%args);
  156. Or the standard Getopt::Long module to permit named arguments:
  157. use Getopt::Long;
  158. GetOptions( "verbose" => \$verbose, # --verbose
  159. "Debug" => \$debug, # --Debug
  160. "output=s" => \$output );
  161. # --output=somestring or --output somestring
  162. Another reason for preprocessing arguments is to make an empty
  163. argument list default to all files:
  164. @ARGV = glob("*") unless @ARGV;
  165. You could even filter out all but plain, text files. This is a bit
  166. silent, of course, and you might prefer to mention them on the way.
  167. @ARGV = grep { -f && -T } @ARGV;
  168. If you're using the B<-n> or B<-p> command-line options, you
  169. should put changes to @ARGV in a C<BEGIN{}> block.
  170. Remember that a normal C<open> has special properties, in that it might
  171. call fopen(3S) or it might called popen(3S), depending on what its
  172. argument looks like; that's why it's sometimes called "magic open".
  173. Here's an example:
  174. $pwdinfo = `domainname` =~ /^(\(none\))?$/
  175. ? '< /etc/passwd'
  176. : 'ypcat passwd |';
  177. open(PWD, $pwdinfo)
  178. or die "can't open $pwdinfo: $!";
  179. This sort of thing also comes into play in filter processing. Because
  180. C<E<lt>ARGVE<gt>> processing employs the normal, shell-style Perl C<open>,
  181. it respects all the special things we've already seen:
  182. $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
  183. That program will read from the file F<f1>, the process F<cmd1>, standard
  184. input (F<tmpfile> in this case), the F<f2> file, the F<cmd2> command,
  185. and finally the F<f3> file.
  186. Yes, this also means that if you have a file named "-" (and so on) in
  187. your directory, that they won't be processed as literal files by C<open>.
  188. You'll need to pass them as "./-" much as you would for the I<rm> program.
  189. Or you could use C<sysopen> as described below.
  190. One of the more interesting applications is to change files of a certain
  191. name into pipes. For example, to autoprocess gzipped or compressed
  192. files by decompressing them with I<gzip>:
  193. @ARGV = map { /^\.(gz|Z)$/ ? "gzip -dc $_ |" : $_ } @ARGV;
  194. Or, if you have the I<GET> program installed from LWP,
  195. you can fetch URLs before processing them:
  196. @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;
  197. It's not for nothing that this is called magic C<E<lt>ARGVE<gt>>.
  198. Pretty nifty, eh?
  199. =head1 Open E<agrave> la C
  200. If you want the convenience of the shell, then Perl's C<open> is
  201. definitely the way to go. On the other hand, if you want finer precision
  202. than C's simplistic fopen(3S) provides, then you should look to Perl's
  203. C<sysopen>, which is a direct hook into the open(2) system call.
  204. That does mean it's a bit more involved, but that's the price of
  205. precision.
  206. C<sysopen> takes 3 (or 4) arguments.
  207. sysopen HANDLE, PATH, FLAGS, [MASK]
  208. The HANDLE argument is a filehandle just as with C<open>. The PATH is
  209. a literal path, one that doesn't pay attention to any greater-thans or
  210. less-thans or pipes or minuses, nor ignore white space. If it's there,
  211. it's part of the path. The FLAGS argument contains one or more values
  212. derived from the Fcntl module that have been or'd together using the
  213. bitwise "|" operator. The final argument, the MASK, is optional; if
  214. present, it is combined with the user's current umask for the creation
  215. mode of the file. You should usually omit this.
  216. Although the traditional values of read-only, write-only, and read-write
  217. are 0, 1, and 2 respectively, this is known not to hold true on some
  218. systems. Instead, it's best to load in the appropriate constants first
  219. from the Fcntl module, which supplies the following standard flags:
  220. O_RDONLY Read only
  221. O_WRONLY Write only
  222. O_RDWR Read and write
  223. O_CREAT Create the file if it doesn't exist
  224. O_EXCL Fail if the file already exists
  225. O_APPEND Append to the file
  226. O_TRUNC Truncate the file
  227. O_NONBLOCK Non-blocking access
  228. Less common flags that are sometimes available on some operating systems
  229. include C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>, C<O_DEFER>,
  230. C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>, C<O_NOCTTY>, C<O_NDELAY>
  231. and C<O_LARGEFILE>. Consult your open(2) manpage or its local equivalent
  232. for details.
  233. Here's how to use C<sysopen> to emulate the simple C<open> calls we had
  234. before. We'll omit the C<|| die $!> checks for clarity, but make sure
  235. you always check the return values in real code. These aren't quite
  236. the same, since C<open> will trim leading and trailing white space,
  237. but you'll get the idea:
  238. To open a file for reading:
  239. open(FH, "< $path");
  240. sysopen(FH, $path, O_RDONLY);
  241. To open a file for writing, creating a new file if needed or else truncating
  242. an old file:
  243. open(FH, "> $path");
  244. sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);
  245. To open a file for appending, creating one if necessary:
  246. open(FH, ">> $path");
  247. sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);
  248. To open a file for update, where the file must already exist:
  249. open(FH, "+< $path");
  250. sysopen(FH, $path, O_RDWR);
  251. And here are things you can do with C<sysopen> that you cannot do with
  252. a regular C<open>. As you see, it's just a matter of controlling the
  253. flags in the third argument.
  254. To open a file for writing, creating a new file which must not previously
  255. exist:
  256. sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);
  257. To open a file for appending, where that file must already exist:
  258. sysopen(FH, $path, O_WRONLY | O_APPEND);
  259. To open a file for update, creating a new file if necessary:
  260. sysopen(FH, $path, O_RDWR | O_CREAT);
  261. To open a file for update, where that file must not already exist:
  262. sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);
  263. To open a file without blocking, creating one if necessary:
  264. sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);
  265. =head2 Permissions E<agrave> la mode
  266. If you omit the MASK argument to C<sysopen>, Perl uses the octal value
  267. 0666. The normal MASK to use for executables and directories should
  268. be 0777, and for anything else, 0666.
  269. Why so permissive? Well, it isn't really. The MASK will be modified
  270. by your process's current C<umask>. A umask is a number representing
  271. I<disabled> permissions bits; that is, bits that will not be turned on
  272. in the created files' permissions field.
  273. For example, if your C<umask> were 027, then the 020 part would
  274. disable the group from writing, and the 007 part would disable others
  275. from reading, writing, or executing. Under these conditions, passing
  276. C<sysopen> 0666 would create a file with mode 0640, since C<0666 &~ 027>
  277. is 0640.
  278. You should seldom use the MASK argument to C<sysopen()>. That takes
  279. away the user's freedom to choose what permission new files will have.
  280. Denying choice is almost always a bad thing. One exception would be for
  281. cases where sensitive or private data is being stored, such as with mail
  282. folders, cookie files, and internal temporary files.
  283. =head1 Obscure Open Tricks
  284. =head2 Re-Opening Files (dups)
  285. Sometimes you already have a filehandle open, and want to make another
  286. handle that's a duplicate of the first one. In the shell, we place an
  287. ampersand in front of a file descriptor number when doing redirections.
  288. For example, C<2E<gt>&1> makes descriptor 2 (that's STDERR in Perl)
  289. be redirected into descriptor 1 (which is usually Perl's STDOUT).
  290. The same is essentially true in Perl: a filename that begins with an
  291. ampersand is treated instead as a file descriptor if a number, or as a
  292. filehandle if a string.
  293. open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
  294. open(MHCONTEXT, "<&4") || die "couldn't dup fd4: $!";
  295. That means that if a function is expecting a filename, but you don't
  296. want to give it a filename because you already have the file open, you
  297. can just pass the filehandle with a leading ampersand. It's best to
  298. use a fully qualified handle though, just in case the function happens
  299. to be in a different package:
  300. somefunction("&main::LOGFILE");
  301. This way if somefunction() is planning on opening its argument, it can
  302. just use the already opened handle. This differs from passing a handle,
  303. because with a handle, you don't open the file. Here you have something
  304. you can pass to open.
  305. If you have one of those tricky, newfangled I/O objects that the C++
  306. folks are raving about, then this doesn't work because those aren't a
  307. proper filehandle in the native Perl sense. You'll have to use fileno()
  308. to pull out the proper descriptor number, assuming you can:
  309. use IO::Socket;
  310. $handle = IO::Socket::INET->new("www.perl.com:80");
  311. $fd = $handle->fileno;
  312. somefunction("&$fd"); # not an indirect function call
  313. It can be easier (and certainly will be faster) just to use real
  314. filehandles though:
  315. use IO::Socket;
  316. local *REMOTE = IO::Socket::INET->new("www.perl.com:80");
  317. die "can't connect" unless defined(fileno(REMOTE));
  318. somefunction("&main::REMOTE");
  319. If the filehandle or descriptor number is preceded not just with a simple
  320. "&" but rather with a "&=" combination, then Perl will not create a
  321. completely new descriptor opened to the same place using the dup(2)
  322. system call. Instead, it will just make something of an alias to the
  323. existing one using the fdopen(3S) library call This is slightly more
  324. parsimonious of systems resources, although this is less a concern
  325. these days. Here's an example of that:
  326. $fd = $ENV{"MHCONTEXTFD"};
  327. open(MHCONTEXT, "<&=$fd") or die "couldn't fdopen $fd: $!";
  328. If you're using magic C<E<lt>ARGVE<gt>>, you could even pass in as a
  329. command line argument in @ARGV something like C<"E<lt>&=$MHCONTEXTFD">,
  330. but we've never seen anyone actually do this.
  331. =head2 Dispelling the Dweomer
  332. Perl is more of a DWIMmer language than something like Java--where DWIM
  333. is an acronym for "do what I mean". But this principle sometimes leads
  334. to more hidden magic than one knows what to do with. In this way, Perl
  335. is also filled with I<dweomer>, an obscure word meaning an enchantment.
  336. Sometimes, Perl's DWIMmer is just too much like dweomer for comfort.
  337. If magic C<open> is a bit too magical for you, you don't have to turn
  338. to C<sysopen>. To open a file with arbitrary weird characters in
  339. it, it's necessary to protect any leading and trailing whitespace.
  340. Leading whitespace is protected by inserting a C<"./"> in front of a
  341. filename that starts with whitespace. Trailing whitespace is protected
  342. by appending an ASCII NUL byte (C<"\0">) at the end off the string.
  343. $file =~ s#^(\s)#./$1#;
  344. open(FH, "< $file\0") || die "can't open $file: $!";
  345. This assumes, of course, that your system considers dot the current
  346. working directory, slash the directory separator, and disallows ASCII
  347. NULs within a valid filename. Most systems follow these conventions,
  348. including all POSIX systems as well as proprietary Microsoft systems.
  349. The only vaguely popular system that doesn't work this way is the
  350. proprietary Macintosh system, which uses a colon where the rest of us
  351. use a slash. Maybe C<sysopen> isn't such a bad idea after all.
  352. If you want to use C<E<lt>ARGVE<gt>> processing in a totally boring
  353. and non-magical way, you could do this first:
  354. # "Sam sat on the ground and put his head in his hands.
  355. # 'I wish I had never come here, and I don't want to see
  356. # no more magic,' he said, and fell silent."
  357. for (@ARGV) {
  358. s#^([^./])#./$1#;
  359. $_ .= "\0";
  360. }
  361. while (<>) {
  362. # now process $_
  363. }
  364. But be warned that users will not appreciate being unable to use "-"
  365. to mean standard input, per the standard convention.
  366. =head2 Paths as Opens
  367. You've probably noticed how Perl's C<warn> and C<die> functions can
  368. produce messages like:
  369. Some warning at scriptname line 29, <FH> chunk 7.
  370. That's because you opened a filehandle FH, and had read in seven records
  371. from it. But what was the name of the file, not the handle?
  372. If you aren't running with C<strict refs>, or if you've turn them off
  373. temporarily, then all you have to do is this:
  374. open($path, "< $path") || die "can't open $path: $!";
  375. while (<$path>) {
  376. # whatever
  377. }
  378. Since you're using the pathname of the file as its handle,
  379. you'll get warnings more like
  380. Some warning at scriptname line 29, </etc/motd> chunk 7.
  381. =head2 Single Argument Open
  382. Remember how we said that Perl's open took two arguments? That was a
  383. passive prevarication. You see, it can also take just one argument.
  384. If and only if the variable is a global variable, not a lexical, you
  385. can pass C<open> just one argument, the filehandle, and it will
  386. get the path from the global scalar variable of the same name.
  387. $FILE = "/etc/motd";
  388. open FILE or die "can't open $FILE: $!";
  389. while (<FILE>) {
  390. # whatever
  391. }
  392. Why is this here? Someone has to cater to the hysterical porpoises.
  393. It's something that's been in Perl since the very beginning, if not
  394. before.
  395. =head2 Playing with STDIN and STDOUT
  396. One clever move with STDOUT is to explicitly close it when you're done
  397. with the program.
  398. END { close(STDOUT) || die "can't close stdout: $!" }
  399. If you don't do this, and your program fills up the disk partition due
  400. to a command line redirection, it won't report the error exit with a
  401. failure status.
  402. You don't have to accept the STDIN and STDOUT you were given. You are
  403. welcome to reopen them if you'd like.
  404. open(STDIN, "< datafile")
  405. || die "can't open datafile: $!";
  406. open(STDOUT, "> output")
  407. || die "can't open output: $!";
  408. And then these can be read directly or passed on to subprocesses.
  409. This makes it look as though the program were initially invoked
  410. with those redirections from the command line.
  411. It's probably more interesting to connect these to pipes. For example:
  412. $pager = $ENV{PAGER} || "(less || more)";
  413. open(STDOUT, "| $pager")
  414. || die "can't fork a pager: $!";
  415. This makes it appear as though your program were called with its stdout
  416. already piped into your pager. You can also use this kind of thing
  417. in conjunction with an implicit fork to yourself. You might do this
  418. if you would rather handle the post processing in your own program,
  419. just in a different process:
  420. head(100);
  421. while (<>) {
  422. print;
  423. }
  424. sub head {
  425. my $lines = shift || 20;
  426. return unless $pid = open(STDOUT, "|-");
  427. die "cannot fork: $!" unless defined $pid;
  428. while (<STDIN>) {
  429. print;
  430. last if --$lines < 0;
  431. }
  432. exit;
  433. }
  434. This technique can be applied to repeatedly push as many filters on your
  435. output stream as you wish.
  436. =head1 Other I/O Issues
  437. These topics aren't really arguments related to C<open> or C<sysopen>,
  438. but they do affect what you do with your open files.
  439. =head2 Opening Non-File Files
  440. When is a file not a file? Well, you could say when it exists but
  441. isn't a plain file. We'll check whether it's a symbolic link first,
  442. just in case.
  443. if (-l $file || ! -f _) {
  444. print "$file is not a plain file\n";
  445. }
  446. What other kinds of files are there than, well, files? Directories,
  447. symbolic links, named pipes, Unix-domain sockets, and block and character
  448. devices. Those are all files, too--just not I<plain> files. This isn't
  449. the same issue as being a text file. Not all text files are plain files.
  450. Not all plain files are textfiles. That's why there are separate C<-f>
  451. and C<-T> file tests.
  452. To open a directory, you should use the C<opendir> function, then
  453. process it with C<readdir>, carefully restoring the directory
  454. name if necessary:
  455. opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
  456. while (defined($file = readdir(DIR))) {
  457. # do something with "$dirname/$file"
  458. }
  459. closedir(DIR);
  460. If you want to process directories recursively, it's better to use the
  461. File::Find module. For example, this prints out all files recursively,
  462. add adds a slash to their names if the file is a directory.
  463. @ARGV = qw(.) unless @ARGV;
  464. use File::Find;
  465. find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
  466. This finds all bogus symbolic links beneath a particular directory:
  467. find sub { print "$File::Find::name\n" if -l && !-e }, $dir;
  468. As you see, with symbolic links, you can just pretend that it is
  469. what it points to. Or, if you want to know I<what> it points to, then
  470. C<readlink> is called for:
  471. if (-l $file) {
  472. if (defined($whither = readlink($file))) {
  473. print "$file points to $whither\n";
  474. } else {
  475. print "$file points nowhere: $!\n";
  476. }
  477. }
  478. Named pipes are a different matter. You pretend they're regular files,
  479. but their opens will normally block until there is both a reader and
  480. a writer. You can read more about them in L<perlipc/"Named Pipes">.
  481. Unix-domain sockets are rather different beasts as well; they're
  482. described in L<perlipc/"Unix-Domain TCP Clients and Servers">.
  483. When it comes to opening devices, it can be easy and it can tricky.
  484. We'll assume that if you're opening up a block device, you know what
  485. you're doing. The character devices are more interesting. These are
  486. typically used for modems, mice, and some kinds of printers. This is
  487. described in L<perlfaq8/"How do I read and write the serial port?">
  488. It's often enough to open them carefully:
  489. sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
  490. # (O_NOCTTY no longer needed on POSIX systems)
  491. or die "can't open /dev/ttyS1: $!";
  492. open(TTYOUT, "+>&TTYIN")
  493. or die "can't dup TTYIN: $!";
  494. $ofh = select(TTYOUT); $| = 1; select($ofh);
  495. print TTYOUT "+++at\015";
  496. $answer = <TTYIN>;
  497. With descriptors that you haven't opened using C<sysopen>, such as a
  498. socket, you can set them to be non-blocking using C<fcntl>:
  499. use Fcntl;
  500. fcntl(Connection, F_SETFL, O_NONBLOCK)
  501. or die "can't set non blocking: $!";
  502. Rather than losing yourself in a morass of twisting, turning C<ioctl>s,
  503. all dissimilar, if you're going to manipulate ttys, it's best to
  504. make calls out to the stty(1) program if you have it, or else use the
  505. portable POSIX interface. To figure this all out, you'll need to read the
  506. termios(3) manpage, which describes the POSIX interface to tty devices,
  507. and then L<POSIX>, which describes Perl's interface to POSIX. There are
  508. also some high-level modules on CPAN that can help you with these games.
  509. Check out Term::ReadKey and Term::ReadLine.
  510. What else can you open? To open a connection using sockets, you won't use
  511. one of Perl's two open functions. See L<perlipc/"Sockets: Client/Server
  512. Communication"> for that. Here's an example. Once you have it,
  513. you can use FH as a bidirectional filehandle.
  514. use IO::Socket;
  515. local *FH = IO::Socket::INET->new("www.perl.com:80");
  516. For opening up a URL, the LWP modules from CPAN are just what
  517. the doctor ordered. There's no filehandle interface, but
  518. it's still easy to get the contents of a document:
  519. use LWP::Simple;
  520. $doc = get('http://www.sn.no/libwww-perl/');
  521. =head2 Binary Files
  522. On certain legacy systems with what could charitably be called terminally
  523. convoluted (some would say broken) I/O models, a file isn't a file--at
  524. least, not with respect to the C standard I/O library. On these old
  525. systems whose libraries (but not kernels) distinguish between text and
  526. binary streams, to get files to behave properly you'll have to bend over
  527. backwards to avoid nasty problems. On such infelicitous systems, sockets
  528. and pipes are already opened in binary mode, and there is currently no
  529. way to turn that off. With files, you have more options.
  530. Another option is to use the C<binmode> function on the appropriate
  531. handles before doing regular I/O on them:
  532. binmode(STDIN);
  533. binmode(STDOUT);
  534. while (<STDIN>) { print }
  535. Passing C<sysopen> a non-standard flag option will also open the file in
  536. binary mode on those systems that support it. This is the equivalent of
  537. opening the file normally, then calling C<binmode>ing on the handle.
  538. sysopen(BINDAT, "records.data", O_RDWR | O_BINARY)
  539. || die "can't open records.data: $!";
  540. Now you can use C<read> and C<print> on that handle without worrying
  541. about the system non-standard I/O library breaking your data. It's not
  542. a pretty picture, but then, legacy systems seldom are. CP/M will be
  543. with us until the end of days, and after.
  544. On systems with exotic I/O systems, it turns out that, astonishingly
  545. enough, even unbuffered I/O using C<sysread> and C<syswrite> might do
  546. sneaky data mutilation behind your back.
  547. while (sysread(WHENCE, $buf, 1024)) {
  548. syswrite(WHITHER, $buf, length($buf));
  549. }
  550. Depending on the vicissitudes of your runtime system, even these calls
  551. may need C<binmode> or C<O_BINARY> first. Systems known to be free of
  552. such difficulties include Unix, the Mac OS, Plan9, and Inferno.
  553. =head2 File Locking
  554. In a multitasking environment, you may need to be careful not to collide
  555. with other processes who want to do I/O on the same files as others
  556. are working on. You'll often need shared or exclusive locks
  557. on files for reading and writing respectively. You might just
  558. pretend that only exclusive locks exist.
  559. Never use the existence of a file C<-e $file> as a locking indication,
  560. because there is a race condition between the test for the existence of
  561. the file and its creation. Atomicity is critical.
  562. Perl's most portable locking interface is via the C<flock> function,
  563. whose simplicity is emulated on systems that don't directly support it,
  564. such as SysV or WindowsNT. The underlying semantics may affect how
  565. it all works, so you should learn how C<flock> is implemented on your
  566. system's port of Perl.
  567. File locking I<does not> lock out another process that would like to
  568. do I/O. A file lock only locks out others trying to get a lock, not
  569. processes trying to do I/O. Because locks are advisory, if one process
  570. uses locking and another doesn't, all bets are off.
  571. By default, the C<flock> call will block until a lock is granted.
  572. A request for a shared lock will be granted as soon as there is no
  573. exclusive locker. A request for a exclusive lock will be granted as
  574. soon as there is no locker of any kind. Locks are on file descriptors,
  575. not file names. You can't lock a file until you open it, and you can't
  576. hold on to a lock once the file has been closed.
  577. Here's how to get a blocking shared lock on a file, typically used
  578. for reading:
  579. use 5.004;
  580. use Fcntl qw(:DEFAULT :flock);
  581. open(FH, "< filename") or die "can't open filename: $!";
  582. flock(FH, LOCK_SH) or die "can't lock filename: $!";
  583. # now read from FH
  584. You can get a non-blocking lock by using C<LOCK_NB>.
  585. flock(FH, LOCK_SH | LOCK_NB)
  586. or die "can't lock filename: $!";
  587. This can be useful for producing more user-friendly behaviour by warning
  588. if you're going to be blocking:
  589. use 5.004;
  590. use Fcntl qw(:DEFAULT :flock);
  591. open(FH, "< filename") or die "can't open filename: $!";
  592. unless (flock(FH, LOCK_SH | LOCK_NB)) {
  593. $| = 1;
  594. print "Waiting for lock...";
  595. flock(FH, LOCK_SH) or die "can't lock filename: $!";
  596. print "got it.\n"
  597. }
  598. # now read from FH
  599. To get an exclusive lock, typically used for writing, you have to be
  600. careful. We C<sysopen> the file so it can be locked before it gets
  601. emptied. You can get a nonblocking version using C<LOCK_EX | LOCK_NB>.
  602. use 5.004;
  603. use Fcntl qw(:DEFAULT :flock);
  604. sysopen(FH, "filename", O_WRONLY | O_CREAT)
  605. or die "can't open filename: $!";
  606. flock(FH, LOCK_EX)
  607. or die "can't lock filename: $!";
  608. truncate(FH, 0)
  609. or die "can't truncate filename: $!";
  610. # now write to FH
  611. Finally, due to the uncounted millions who cannot be dissuaded from
  612. wasting cycles on useless vanity devices called hit counters, here's
  613. how to increment a number in a file safely:
  614. use Fcntl qw(:DEFAULT :flock);
  615. sysopen(FH, "numfile", O_RDWR | O_CREAT)
  616. or die "can't open numfile: $!";
  617. # autoflush FH
  618. $ofh = select(FH); $| = 1; select ($ofh);
  619. flock(FH, LOCK_EX)
  620. or die "can't write-lock numfile: $!";
  621. $num = <FH> || 0;
  622. seek(FH, 0, 0)
  623. or die "can't rewind numfile : $!";
  624. print FH $num+1, "\n"
  625. or die "can't write numfile: $!";
  626. truncate(FH, tell(FH))
  627. or die "can't truncate numfile: $!";
  628. close(FH)
  629. or die "can't close numfile: $!";
  630. =head1 SEE ALSO
  631. The C<open> and C<sysopen> function in perlfunc(1);
  632. the standard open(2), dup(2), fopen(3), and fdopen(3) manpages;
  633. the POSIX documentation.
  634. =head1 AUTHOR and COPYRIGHT
  635. Copyright 1998 Tom Christiansen.
  636. When included as part of the Standard Version of Perl, or as part of
  637. its complete documentation whether printed or otherwise, this work may
  638. be distributed only under the terms of Perl's Artistic License. Any
  639. distribution of this file or derivatives thereof outside of that
  640. package require that special arrangements be made with copyright
  641. holder.
  642. Irrespective of its distribution, all code examples in these files are
  643. hereby placed into the public domain. You are permitted and
  644. encouraged to use this code in your own programs for fun or for profit
  645. as you see fit. A simple comment in the code giving credit would be
  646. courteous but is not required.
  647. =head1 HISTORY
  648. First release: Sat Jan 9 08:09:11 MST 1999