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