perl 3.0 patch #37 (combined patch)
[p5sagit/p5-mst-13.2.git] / perl.man.2
1 ''' Beginning of part 2
2 ''' $Header: perl_man.2,v 3.0.1.9 90/10/15 18:17:37 lwall Locked $
3 '''
4 ''' $Log:       perl.man.2,v $
5 ''' Revision 3.0.1.9  90/10/15  18:17:37  lwall
6 ''' patch29: added caller
7 ''' patch29: index and substr now have optional 3rd args
8 ''' patch29: added SysV IPC
9 ''' 
10 ''' Revision 3.0.1.8  90/08/13  22:21:00  lwall
11 ''' patch28: documented that you can't interpolate $) or $| in pattern
12 ''' 
13 ''' Revision 3.0.1.7  90/08/09  04:27:04  lwall
14 ''' patch19: added require operator
15 ''' 
16 ''' Revision 3.0.1.6  90/08/03  11:15:29  lwall
17 ''' patch19: Intermediate diffs for Randal
18 ''' 
19 ''' Revision 3.0.1.5  90/03/27  16:15:17  lwall
20 ''' patch16: MSDOS support
21 ''' 
22 ''' Revision 3.0.1.4  90/03/12  16:46:02  lwall
23 ''' patch13: documented behavior of @array = /noparens/
24 ''' 
25 ''' Revision 3.0.1.3  90/02/28  17:55:58  lwall
26 ''' patch9: grep now returns number of items matched in scalar context
27 ''' patch9: documented in-place modification capabilites of grep
28 ''' 
29 ''' Revision 3.0.1.2  89/11/17  15:30:16  lwall
30 ''' patch5: fixed some manual typos and indent problems
31 ''' 
32 ''' Revision 3.0.1.1  89/11/11  04:43:10  lwall
33 ''' patch2: made some line breaks depend on troff vs. nroff
34 ''' patch2: example of unshift had args backwards
35 ''' 
36 ''' Revision 3.0  89/10/18  15:21:37  lwall
37 ''' 3.0 baseline
38 ''' 
39 '''
40 .PP
41 Along with the literals and variables mentioned earlier,
42 the operations in the following section can serve as terms in an expression.
43 Some of these operations take a LIST as an argument.
44 Such a list can consist of any combination of scalar arguments or array values;
45 the array values will be included in the list as if each individual element were
46 interpolated at that point in the list, forming a longer single-dimensional
47 array value.
48 Elements of the LIST should be separated by commas.
49 If an operation is listed both with and without parentheses around its
50 arguments, it means you can either use it as a unary operator or
51 as a function call.
52 To use it as a function call, the next token on the same line must
53 be a left parenthesis.
54 (There may be intervening white space.)
55 Such a function then has highest precedence, as you would expect from
56 a function.
57 If any token other than a left parenthesis follows, then it is a
58 unary operator, with a precedence depending only on whether it is a LIST
59 operator or not.
60 LIST operators have lowest precedence.
61 All other unary operators have a precedence greater than relational operators
62 but less than arithmetic operators.
63 See the section on Precedence.
64 .Ip "/PATTERN/" 8 4
65 See m/PATTERN/.
66 .Ip "?PATTERN?" 8 4
67 This is just like the /pattern/ search, except that it matches only once between
68 calls to the
69 .I reset
70 operator.
71 This is a useful optimization when you only want to see the first occurrence of
72 something in each file of a set of files, for instance.
73 Only ?? patterns local to the current package are reset.
74 .Ip "accept(NEWSOCKET,GENERICSOCKET)" 8 2
75 Does the same thing that the accept system call does.
76 Returns true if it succeeded, false otherwise.
77 See example in section on Interprocess Communication.
78 .Ip "atan2(X,Y)" 8 2
79 Returns the arctangent of X/Y in the range
80 .if t \-\(*p to \(*p.
81 .if n \-PI to PI.
82 .Ip "bind(SOCKET,NAME)" 8 2
83 Does the same thing that the bind system call does.
84 Returns true if it succeeded, false otherwise.
85 NAME should be a packed address of the proper type for the socket.
86 See example in section on Interprocess Communication.
87 .Ip "binmode(FILEHANDLE)" 8 4
88 .Ip "binmode FILEHANDLE" 8 4
89 Arranges for the file to be read in \*(L"binary\*(R" mode in operating systems
90 that distinguish between binary and text files.
91 Files that are not read in binary mode have CR LF sequences translated
92 to LF on input and LF translated to CR LF on output.
93 Binmode has no effect under Unix.
94 If FILEHANDLE is an expression, the value is taken as the name of
95 the filehandle.
96 .Ip "caller(EXPR)"
97 .Ip "caller"
98 Returns the context of the current subroutine call:
99 .nf
100
101         ($package,$filename,$line) = caller;
102
103 .fi
104 With EXPR, returns some extra information that the debugger uses to print
105 a stack trace.  The value of EXPR indicates how many call frames to go
106 back before the current one.
107 .Ip "chdir(EXPR)" 8 2
108 .Ip "chdir EXPR" 8 2
109 Changes the working directory to EXPR, if possible.
110 If EXPR is omitted, changes to home directory.
111 Returns 1 upon success, 0 otherwise.
112 See example under
113 .IR die .
114 .Ip "chmod(LIST)" 8 2
115 .Ip "chmod LIST" 8 2
116 Changes the permissions of a list of files.
117 The first element of the list must be the numerical mode.
118 Returns the number of files successfully changed.
119 .nf
120
121 .ne 2
122         $cnt = chmod 0755, \'foo\', \'bar\';
123         chmod 0755, @executables;
124
125 .fi
126 .Ip "chop(LIST)" 8 7
127 .Ip "chop(VARIABLE)" 8
128 .Ip "chop VARIABLE" 8
129 .Ip "chop" 8
130 Chops off the last character of a string and returns the character chopped.
131 It's used primarily to remove the newline from the end of an input record,
132 but is much more efficient than s/\en// because it neither scans nor copies
133 the string.
134 If VARIABLE is omitted, chops $_.
135 Example:
136 .nf
137
138 .ne 5
139         while (<>) {
140                 chop;   # avoid \en on last field
141                 @array = split(/:/);
142                 .\|.\|.
143         }
144
145 .fi
146 You can actually chop anything that's an lvalue, including an assignment:
147 .nf
148
149         chop($cwd = \`pwd\`);
150         chop($answer = <STDIN>);
151
152 .fi
153 If you chop a list, each element is chopped.
154 Only the value of the last chop is returned.
155 .Ip "chown(LIST)" 8 2
156 .Ip "chown LIST" 8 2
157 Changes the owner (and group) of a list of files.
158 The first two elements of the list must be the NUMERICAL uid and gid,
159 in that order.
160 Returns the number of files successfully changed.
161 .nf
162
163 .ne 2
164         $cnt = chown $uid, $gid, \'foo\', \'bar\';
165         chown $uid, $gid, @filenames;
166
167 .fi
168 .ne 23
169 Here's an example of looking up non-numeric uids:
170 .nf
171
172         print "User: ";
173         $user = <STDIN>;
174         chop($user);
175         print "Files: "
176         $pattern = <STDIN>;
177         chop($pattern);
178 .ie t \{\
179         open(pass, \'/etc/passwd\') || die "Can't open passwd: $!\en";
180 'br\}
181 .el \{\
182         open(pass, \'/etc/passwd\')
183                 || die "Can't open passwd: $!\en";
184 'br\}
185         while (<pass>) {
186                 ($login,$pass,$uid,$gid) = split(/:/);
187                 $uid{$login} = $uid;
188                 $gid{$login} = $gid;
189         }
190         @ary = <${pattern}>;    # get filenames
191         if ($uid{$user} eq \'\') {
192                 die "$user not in passwd file";
193         }
194         else {
195                 chown $uid{$user}, $gid{$user}, @ary;
196         }
197
198 .fi
199 .Ip "chroot(FILENAME)" 8 5
200 .Ip "chroot FILENAME" 8
201 Does the same as the system call of that name.
202 If you don't know what it does, don't worry about it.
203 If FILENAME is omitted, does chroot to $_.
204 .Ip "close(FILEHANDLE)" 8 5
205 .Ip "close FILEHANDLE" 8
206 Closes the file or pipe associated with the file handle.
207 You don't have to close FILEHANDLE if you are immediately going to
208 do another open on it, since open will close it for you.
209 (See
210 .IR open .)
211 However, an explicit close on an input file resets the line counter ($.), while
212 the implicit close done by
213 .I open
214 does not.
215 Also, closing a pipe will wait for the process executing on the pipe to complete,
216 in case you want to look at the output of the pipe afterwards.
217 Closing a pipe explicitly also puts the status value of the command into $?.
218 Example:
219 .nf
220
221 .ne 4
222         open(OUTPUT, \'|sort >foo\');   # pipe to sort
223         .\|.\|. # print stuff to output
224         close OUTPUT;           # wait for sort to finish
225         open(INPUT, \'foo\');   # get sort's results
226
227 .fi
228 FILEHANDLE may be an expression whose value gives the real filehandle name.
229 .Ip "closedir(DIRHANDLE)" 8 5
230 .Ip "closedir DIRHANDLE" 8
231 Closes a directory opened by opendir().
232 .Ip "connect(SOCKET,NAME)" 8 2
233 Does the same thing that the connect system call does.
234 Returns true if it succeeded, false otherwise.
235 NAME should be a package address of the proper type for the socket.
236 See example in section on Interprocess Communication.
237 .Ip "cos(EXPR)" 8 6
238 .Ip "cos EXPR" 8 6
239 Returns the cosine of EXPR (expressed in radians).
240 If EXPR is omitted takes cosine of $_.
241 .Ip "crypt(PLAINTEXT,SALT)" 8 6
242 Encrypts a string exactly like the crypt() function in the C library.
243 Useful for checking the password file for lousy passwords.
244 Only the guys wearing white hats should do this.
245 .Ip "dbmclose(ASSOC_ARRAY)" 8 6
246 .Ip "dbmclose ASSOC_ARRAY" 8
247 Breaks the binding between a dbm file and an associative array.
248 The values remaining in the associative array are meaningless unless
249 you happen to want to know what was in the cache for the dbm file.
250 This function is only useful if you have ndbm.
251 .Ip "dbmopen(ASSOC,DBNAME,MODE)" 8 6
252 This binds a dbm or ndbm file to an associative array.
253 ASSOC is the name of the associative array.
254 (Unlike normal open, the first argument is NOT a filehandle, even though
255 it looks like one).
256 DBNAME is the name of the database (without the .dir or .pag extension).
257 If the database does not exist, it is created with protection specified
258 by MODE (as modified by the umask).
259 If your system only supports the older dbm functions, you may only have one
260 dbmopen in your program.
261 If your system has neither dbm nor ndbm, calling dbmopen produces a fatal
262 error.
263 .Sp
264 Values assigned to the associative array prior to the dbmopen are lost.
265 A certain number of values from the dbm file are cached in memory.
266 By default this number is 64, but you can increase it by preallocating
267 that number of garbage entries in the associative array before the dbmopen.
268 You can flush the cache if necessary with the reset command.
269 .Sp
270 If you don't have write access to the dbm file, you can only read
271 associative array variables, not set them.
272 If you want to test whether you can write, either use file tests or
273 try setting a dummy array entry inside an eval, which will trap the error.
274 .Sp
275 Note that functions such as keys() and values() may return huge array values
276 when used on large dbm files.
277 You may prefer to use the each() function to iterate over large dbm files.
278 Example:
279 .nf
280
281 .ne 6
282         # print out history file offsets
283         dbmopen(HIST,'/usr/lib/news/history',0666);
284         while (($key,$val) = each %HIST) {
285                 print $key, ' = ', unpack('L',$val), "\en";
286         }
287         dbmclose(HIST);
288
289 .fi
290 .Ip "defined(EXPR)" 8 6
291 .Ip "defined EXPR" 8
292 Returns a boolean value saying whether the lvalue EXPR has a real value
293 or not.
294 Many operations return the undefined value under exceptional conditions,
295 such as end of file, uninitialized variable, system error and such.
296 This function allows you to distinguish between an undefined null string
297 and a defined null string with operations that might return a real null
298 string, in particular referencing elements of an array.
299 You may also check to see if arrays or subroutines exist.
300 Use on predefined variables is not guaranteed to produce intuitive results.
301 Examples:
302 .nf
303
304 .ne 7
305         print if defined $switch{'D'};
306         print "$val\en" while defined($val = pop(@ary));
307         die "Can't readlink $sym: $!"
308                 unless defined($value = readlink $sym);
309         eval '@foo = ()' if defined(@foo);
310         die "No XYZ package defined" unless defined %_XYZ;
311         sub foo { defined &bar ? &bar(@_) : die "No bar"; }
312
313 .fi
314 See also undef.
315 .Ip "delete $ASSOC{KEY}" 8 6
316 Deletes the specified value from the specified associative array.
317 Returns the deleted value, or the undefined value if nothing was deleted.
318 Deleting from $ENV{} modifies the environment.
319 Deleting from an array bound to a dbm file deletes the entry from the dbm
320 file.
321 .Sp
322 The following deletes all the values of an associative array:
323 .nf
324
325 .ne 3
326         foreach $key (keys %ARRAY) {
327                 delete $ARRAY{$key};
328         }
329
330 .fi
331 (But it would be faster to use the
332 .I reset
333 command.
334 Saying undef %ARRAY is faster yet.)
335 .Ip "die(LIST)" 8
336 .Ip "die LIST" 8
337 Prints the value of LIST to
338 .I STDERR
339 and exits with the current value of $!
340 (errno).
341 If $! is 0, exits with the value of ($? >> 8) (\`command\` status).
342 If ($? >> 8) is 0, exits with 255.
343 Equivalent examples:
344 .nf
345
346 .ne 3
347 .ie t \{\
348         die "Can't cd to spool: $!\en" unless chdir \'/usr/spool/news\';
349 'br\}
350 .el \{\
351         die "Can't cd to spool: $!\en"
352                 unless chdir \'/usr/spool/news\';
353 'br\}
354
355         chdir \'/usr/spool/news\' || die "Can't cd to spool: $!\en" 
356
357 .fi
358 .Sp
359 If the value of EXPR does not end in a newline, the current script line
360 number and input line number (if any) are also printed, and a newline is
361 supplied.
362 Hint: sometimes appending \*(L", stopped\*(R" to your message will cause it to make
363 better sense when the string \*(L"at foo line 123\*(R" is appended.
364 Suppose you are running script \*(L"canasta\*(R".
365 .nf
366
367 .ne 7
368         die "/etc/games is no good";
369         die "/etc/games is no good, stopped";
370
371 produce, respectively
372
373         /etc/games is no good at canasta line 123.
374         /etc/games is no good, stopped at canasta line 123.
375
376 .fi
377 See also
378 .IR exit .
379 .Ip "do BLOCK" 8 4
380 Returns the value of the last command in the sequence of commands indicated
381 by BLOCK.
382 When modified by a loop modifier, executes the BLOCK once before testing the
383 loop condition.
384 (On other statements the loop modifiers test the conditional first.)
385 .Ip "do SUBROUTINE (LIST)" 8 3
386 Executes a SUBROUTINE declared by a
387 .I sub
388 declaration, and returns the value
389 of the last expression evaluated in SUBROUTINE.
390 If there is no subroutine by that name, produces a fatal error.
391 (You may use the \*(L"defined\*(R" operator to determine if a subroutine
392 exists.)
393 If you pass arrays as part of LIST you may wish to pass the length
394 of the array in front of each array.
395 (See the section on subroutines later on.)
396 SUBROUTINE may be a scalar variable, in which case the variable contains
397 the name of the subroutine to execute.
398 The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R"
399 form.
400 .Sp
401 As an alternate form, you may call a subroutine by prefixing the name with
402 an ampersand: &foo(@args).
403 If you aren't passing any arguments, you don't have to use parentheses.
404 If you omit the parentheses, no @_ array is passed to the subroutine.
405 The & form is also used to specify subroutines to the defined and undef
406 operators.
407 .Ip "do EXPR" 8 3
408 Uses the value of EXPR as a filename and executes the contents of the file
409 as a
410 .I perl
411 script.
412 Its primary use is to include subroutines from a
413 .I perl
414 subroutine library.
415 .nf
416
417         do \'stat.pl\';
418
419 is just like
420
421         eval \`cat stat.pl\`;
422
423 .fi
424 except that it's more efficient, more concise, keeps track of the current
425 filename for error messages, and searches all the
426 .B \-I
427 libraries if the file
428 isn't in the current directory (see also the @INC array in Predefined Names).
429 It's the same, however, in that it does reparse the file every time you
430 call it, so if you are going to use the file inside a loop you might prefer
431 to use \-P and #include, at the expense of a little more startup time.
432 (The main problem with #include is that cpp doesn't grok # comments\*(--a
433 workaround is to use \*(L";#\*(R" for standalone comments.)
434 Note that the following are NOT equivalent:
435 .nf
436
437 .ne 2
438         do $foo;        # eval a file
439         do $foo();      # call a subroutine
440
441 .fi
442 Note that inclusion of library routines is better done with
443 the \*(L"require\*(R" operator.
444 .Ip "dump LABEL" 8 6
445 This causes an immediate core dump.
446 Primarily this is so that you can use the undump program to turn your
447 core dump into an executable binary after having initialized all your
448 variables at the beginning of the program.
449 When the new binary is executed it will begin by executing a "goto LABEL"
450 (with all the restrictions that goto suffers).
451 Think of it as a goto with an intervening core dump and reincarnation.
452 If LABEL is omitted, restarts the program from the top.
453 WARNING: any files opened at the time of the dump will NOT be open any more
454 when the program is reincarnated, with possible resulting confusion on the part
455 of perl.
456 See also \-u.
457 .Sp
458 Example:
459 .nf
460
461 .ne 16
462         #!/usr/bin/perl
463         require 'getopt.pl';
464         require 'stat.pl';
465         %days = (
466             'Sun',1,
467             'Mon',2,
468             'Tue',3,
469             'Wed',4,
470             'Thu',5,
471             'Fri',6,
472             'Sat',7);
473
474         dump QUICKSTART if $ARGV[0] eq '-d';
475
476     QUICKSTART:
477         do Getopt('f');
478
479 .fi
480 .Ip "each(ASSOC_ARRAY)" 8 6
481 .Ip "each ASSOC_ARRAY" 8
482 Returns a 2 element array consisting of the key and value for the next
483 value of an associative array, so that you can iterate over it.
484 Entries are returned in an apparently random order.
485 When the array is entirely read, a null array is returned (which when
486 assigned produces a FALSE (0) value).
487 The next call to each() after that will start iterating again.
488 The iterator can be reset only by reading all the elements from the array.
489 You must not modify the array while iterating over it.
490 There is a single iterator for each associative array, shared by all
491 each(), keys() and values() function calls in the program.
492 The following prints out your environment like the printenv program, only
493 in a different order:
494 .nf
495
496 .ne 3
497         while (($key,$value) = each %ENV) {
498                 print "$key=$value\en";
499         }
500
501 .fi
502 See also keys() and values().
503 .Ip "eof(FILEHANDLE)" 8 8
504 .Ip "eof()" 8
505 .Ip "eof" 8
506 Returns 1 if the next read on FILEHANDLE will return end of file, or if
507 FILEHANDLE is not open.
508 FILEHANDLE may be an expression whose value gives the real filehandle name.
509 (Note that this function actually reads a character and then ungetc's it,
510 so it is not very useful in an interactive context.)
511 An eof without an argument returns the eof status for the last file read.
512 Empty parentheses () may be used to indicate the pseudo file formed of the
513 files listed on the command line, i.e. eof() is reasonable to use inside
514 a while (<>) loop to detect the end of only the last file.
515 Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop.
516 Examples:
517 .nf
518
519 .ne 7
520         # insert dashes just before last line of last file
521         while (<>) {
522                 if (eof()) {
523                         print "\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\en";
524                 }
525                 print;
526         }
527
528 .ne 7
529         # reset line numbering on each input file
530         while (<>) {
531                 print "$.\et$_";
532                 if (eof) {      # Not eof().
533                         close(ARGV);
534                 }
535         }
536
537 .fi
538 .Ip "eval(EXPR)" 8 6
539 .Ip "eval EXPR" 8 6
540 EXPR is parsed and executed as if it were a little
541 .I perl
542 program.
543 It is executed in the context of the current
544 .I perl
545 program, so that
546 any variable settings, subroutine or format definitions remain afterwards.
547 The value returned is the value of the last expression evaluated, just
548 as with subroutines.
549 If there is a syntax error or runtime error, a null string is returned by
550 eval, and $@ is set to the error message.
551 If there was no error, $@ is null.
552 If EXPR is omitted, evaluates $_.
553 The final semicolon, if any, may be omitted from the expression.
554 .Sp
555 Note that, since eval traps otherwise-fatal errors, it is useful for
556 determining whether a particular feature
557 (such as dbmopen or symlink) is implemented.
558 .Ip "exec(LIST)" 8 8
559 .Ip "exec LIST" 8 6
560 If there is more than one argument in LIST, or if LIST is an array with
561 more than one value,
562 calls execvp() with the arguments in LIST.
563 If there is only one scalar argument, the argument is checked for shell metacharacters.
564 If there are any, the entire argument is passed to \*(L"/bin/sh \-c\*(R" for parsing.
565 If there are none, the argument is split into words and passed directly to
566 execvp(), which is more efficient.
567 Note: exec (and system) do not flush your output buffer, so you may need to
568 set $| to avoid lost output.
569 Examples:
570 .nf
571
572         exec \'/bin/echo\', \'Your arguments are: \', @ARGV;
573         exec "sort $outfile | uniq";
574
575 .fi
576 .Sp
577 If you don't really want to execute the first argument, but want to lie
578 to the program you are executing about its own name, you can specify
579 the program you actually want to run by assigning that to a variable and
580 putting the name of the variable in front of the LIST without a comma.
581 (This always forces interpretation of the LIST as a multi-valued list, even
582 if there is only a single scalar in the list.)
583 Example:
584 .nf
585
586 .ne 2
587         $shell = '/bin/csh';
588         exec $shell '-sh';              # pretend it's a login shell
589
590 .fi
591 .Ip "exit(EXPR)" 8 6
592 .Ip "exit EXPR" 8
593 Evaluates EXPR and exits immediately with that value.
594 Example:
595 .nf
596
597 .ne 2
598         $ans = <STDIN>;
599         exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;
600
601 .fi
602 See also
603 .IR die .
604 If EXPR is omitted, exits with 0 status.
605 .Ip "exp(EXPR)" 8 3
606 .Ip "exp EXPR" 8
607 Returns
608 .I e
609 to the power of EXPR.
610 If EXPR is omitted, gives exp($_).
611 .Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
612 Implements the fcntl(2) function.
613 You'll probably have to say
614 .nf
615
616         require "fcntl.ph";     # probably /usr/local/lib/perl/fcntl.ph
617
618 .fi
619 first to get the correct function definitions.
620 If fcntl.h doesn't exist or doesn't have the correct definitions
621 you'll have to roll
622 your own, based on your C header files such as <sys/fcntl.h>.
623 (There is a perl script called makelib that comes with the perl kit
624 which may help you in this.)
625 Argument processing and value return works just like ioctl below.
626 Note that fcntl will produce a fatal error if used on a machine that doesn't implement
627 fcntl(2).
628 .Ip "fileno(FILEHANDLE)" 8 4
629 .Ip "fileno FILEHANDLE" 8 4
630 Returns the file descriptor for a filehandle.
631 Useful for constructing bitmaps for select().
632 If FILEHANDLE is an expression, the value is taken as the name of
633 the filehandle.
634 .Ip "flock(FILEHANDLE,OPERATION)" 8 4
635 Calls flock(2) on FILEHANDLE.
636 See manual page for flock(2) for definition of OPERATION.
637 Will produce a fatal error if used on a machine that doesn't implement
638 flock(2).
639 Here's a mailbox appender for BSD systems.
640 .nf
641
642 .ne 20
643         $LOCK_SH = 1;
644         $LOCK_EX = 2;
645         $LOCK_NB = 4;
646         $LOCK_UN = 8;
647
648         sub lock {
649             flock(MBOX,$LOCK_EX);
650             # and, in case someone appended
651             # while we were waiting...
652             seek(MBOX, 0, 2);
653         }
654
655         sub unlock {
656             flock(MBOX,$LOCK_UN);
657         }
658
659         open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
660                 || die "Can't open mailbox: $!";
661
662         do lock();
663         print MBOX $msg,"\en\en";
664         do unlock();
665
666 .fi
667 .Ip "fork" 8 4
668 Does a fork() call.
669 Returns the child pid to the parent process and 0 to the child process.
670 Note: unflushed buffers remain unflushed in both processes, which means
671 you may need to set $| to avoid duplicate output.
672 .Ip "getc(FILEHANDLE)" 8 4
673 .Ip "getc FILEHANDLE" 8
674 .Ip "getc" 8
675 Returns the next character from the input file attached to FILEHANDLE, or
676 a null string at EOF.
677 If FILEHANDLE is omitted, reads from STDIN.
678 .Ip "getlogin" 8 3
679 Returns the current login from /etc/utmp, if any.
680 If null, use getpwuid.
681
682         $login = getlogin || (getpwuid($<))[0] || "Somebody";
683
684 .Ip "getpeername(SOCKET)" 8 3
685 Returns the packed sockaddr address of other end of the SOCKET connection.
686 .nf
687
688 .ne 4
689         # An internet sockaddr
690         $sockaddr = 'S n a4 x8';
691         $hersockaddr = getpeername(S);
692 .ie t \{\
693         ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
694 'br\}
695 .el \{\
696         ($family, $port, $heraddr) =
697                         unpack($sockaddr,$hersockaddr);
698 'br\}
699
700 .fi
701 .Ip "getpgrp(PID)" 8 4
702 .Ip "getpgrp PID" 8
703 Returns the current process group for the specified PID, 0 for the current
704 process.
705 Will produce a fatal error if used on a machine that doesn't implement
706 getpgrp(2).
707 If EXPR is omitted, returns process group of current process.
708 .Ip "getppid" 8 4
709 Returns the process id of the parent process.
710 .Ip "getpriority(WHICH,WHO)" 8 4
711 Returns the current priority for a process, a process group, or a user.
712 (See getpriority(2).)
713 Will produce a fatal error if used on a machine that doesn't implement
714 getpriority(2).
715 .Ip "getpwnam(NAME)" 8
716 .Ip "getgrnam(NAME)" 8
717 .Ip "gethostbyname(NAME)" 8
718 .Ip "getnetbyname(NAME)" 8
719 .Ip "getprotobyname(NAME)" 8
720 .Ip "getpwuid(UID)" 8
721 .Ip "getgrgid(GID)" 8
722 .Ip "getservbyname(NAME,PROTO)" 8
723 .Ip "gethostbyaddr(ADDR,ADDRTYPE)" 8
724 .Ip "getnetbyaddr(ADDR,ADDRTYPE)" 8
725 .Ip "getprotobynumber(NUMBER)" 8
726 .Ip "getservbyport(PORT,PROTO)" 8
727 .Ip "getpwent" 8
728 .Ip "getgrent" 8
729 .Ip "gethostent" 8
730 .Ip "getnetent" 8
731 .Ip "getprotoent" 8
732 .Ip "getservent" 8
733 .Ip "setpwent" 8
734 .Ip "setgrent" 8
735 .Ip "sethostent(STAYOPEN)" 8
736 .Ip "setnetent(STAYOPEN)" 8
737 .Ip "setprotoent(STAYOPEN)" 8
738 .Ip "setservent(STAYOPEN)" 8
739 .Ip "endpwent" 8
740 .Ip "endgrent" 8
741 .Ip "endhostent" 8
742 .Ip "endnetent" 8
743 .Ip "endprotoent" 8
744 .Ip "endservent" 8
745 These routines perform the same functions as their counterparts in the
746 system library.
747 The return values from the various get routines are as follows:
748 .nf
749
750         ($name,$passwd,$uid,$gid,
751            $quota,$comment,$gcos,$dir,$shell) = getpw.\|.\|.
752         ($name,$passwd,$gid,$members) = getgr.\|.\|.
753         ($name,$aliases,$addrtype,$length,@addrs) = gethost.\|.\|.
754         ($name,$aliases,$addrtype,$net) = getnet.\|.\|.
755         ($name,$aliases,$proto) = getproto.\|.\|.
756         ($name,$aliases,$port,$proto) = getserv.\|.\|.
757
758 .fi
759 The $members value returned by getgr.\|.\|. is a space separated list
760 of the login names of the members of the group.
761 .Sp
762 The @addrs value returned by the gethost.\|.\|. functions is a list of the
763 raw addresses returned by the corresponding system library call.
764 In the Internet domain, each address is four bytes long and you can unpack
765 it by saying something like:
766 .nf
767
768         ($a,$b,$c,$d) = unpack('C4',$addr[0]);
769
770 .fi
771 .Ip "getsockname(SOCKET)" 8 3
772 Returns the packed sockaddr address of this end of the SOCKET connection.
773 .nf
774
775 .ne 4
776         # An internet sockaddr
777         $sockaddr = 'S n a4 x8';
778         $mysockaddr = getsockname(S);
779 .ie t \{\
780         ($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr);
781 'br\}
782 .el \{\
783         ($family, $port, $myaddr) =
784                         unpack($sockaddr,$mysockaddr);
785 'br\}
786
787 .fi
788 .Ip "getsockopt(SOCKET,LEVEL,OPTNAME)" 8 3
789 Returns the socket option requested, or undefined if there is an error.
790 .Ip "gmtime(EXPR)" 8 4
791 .Ip "gmtime EXPR" 8
792 Converts a time as returned by the time function to a 9-element array with
793 the time analyzed for the Greenwich timezone.
794 Typically used as follows:
795 .nf
796
797 .ne 3
798 .ie t \{\
799     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
800 'br\}
801 .el \{\
802     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
803                                                 gmtime(time);
804 'br\}
805
806 .fi
807 All array elements are numeric, and come straight out of a struct tm.
808 In particular this means that $mon has the range 0.\|.11 and $wday has the
809 range 0.\|.6.
810 If EXPR is omitted, does gmtime(time).
811 .Ip "goto LABEL" 8 6
812 Finds the statement labeled with LABEL and resumes execution there.
813 Currently you may only go to statements in the main body of the program
814 that are not nested inside a do {} construct.
815 This statement is not implemented very efficiently, and is here only to make
816 the
817 .IR sed -to- perl
818 translator easier.
819 I may change its semantics at any time, consistent with support for translated
820 .I sed
821 scripts.
822 Use it at your own risk.
823 Better yet, don't use it at all.
824 .Ip "grep(EXPR,LIST)" 8 4
825 Evaluates EXPR for each element of LIST (locally setting $_ to each element)
826 and returns the array value consisting of those elements for which the
827 expression evaluated to true.
828 In a scalar context, returns the number of times the expression was true.
829 .nf
830
831         @foo = grep(!/^#/, @bar);    # weed out comments
832
833 .fi
834 Note that, since $_ is a reference into the array value, it can be
835 used to modify the elements of the array.
836 While this is useful and supported, it can cause bizarre results if
837 the LIST is not a named array.
838 .Ip "hex(EXPR)" 8 4
839 .Ip "hex EXPR" 8
840 Returns the decimal value of EXPR interpreted as an hex string.
841 (To interpret strings that might start with 0 or 0x see oct().)
842 If EXPR is omitted, uses $_.
843 .Ip "index(STR,SUBSTR,POSITION)" 8 4
844 .Ip "index(STR,SUBSTR)" 8 4
845 Returns the position of the first occurrence of SUBSTR in STR at or after
846 POSITION.
847 If POSITION is omitted, starts searching from the beginning of the string.
848 The return value is based at 0, or whatever you've
849 set the $[ variable to.
850 If the substring is not found, returns one less than the base, ordinarily \-1.
851 .Ip "int(EXPR)" 8 4
852 .Ip "int EXPR" 8
853 Returns the integer portion of EXPR.
854 If EXPR is omitted, uses $_.
855 .Ip "ioctl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
856 Implements the ioctl(2) function.
857 You'll probably have to say
858 .nf
859
860         require "ioctl.ph";     # probably /usr/local/lib/perl/ioctl.ph
861
862 .fi
863 first to get the correct function definitions.
864 If ioctl.h doesn't exist or doesn't have the correct definitions
865 you'll have to roll
866 your own, based on your C header files such as <sys/ioctl.h>.
867 (There is a perl script called makelib that comes with the perl kit
868 which may help you in this.)
869 SCALAR will be read and/or written depending on the FUNCTION\*(--a pointer
870 to the string value of SCALAR will be passed as the third argument of
871 the actual ioctl call.
872 (If SCALAR has no string value but does have a numeric value, that value
873 will be passed rather than a pointer to the string value.
874 To guarantee this to be true, add a 0 to the scalar before using it.)
875 The pack() and unpack() functions are useful for manipulating the values
876 of structures used by ioctl().
877 The following example sets the erase character to DEL.
878 .nf
879
880 .ne 9
881         require 'ioctl.ph';
882         $sgttyb_t = "ccccs";            # 4 chars and a short
883         if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
884                 @ary = unpack($sgttyb_t,$sgttyb);
885                 $ary[2] = 127;
886                 $sgttyb = pack($sgttyb_t,@ary);
887                 ioctl(STDIN,$TIOCSETP,$sgttyb)
888                         || die "Can't ioctl: $!";
889         }
890
891 .fi
892 The return value of ioctl (and fcntl) is as follows:
893 .nf
894
895 .ne 4
896         if OS returns:\h'|3i'perl returns:
897           -1\h'|3i'  undefined value
898           0\h'|3i'  string "0 but true"
899           anything else\h'|3i'  that number
900
901 .fi
902 Thus perl returns true on success and false on failure, yet you can still
903 easily determine the actual value returned by the operating system:
904 .nf
905
906         ($retval = ioctl(...)) || ($retval = -1);
907         printf "System returned %d\en", $retval;
908 .fi
909 .Ip "join(EXPR,LIST)" 8 8
910 .Ip "join(EXPR,ARRAY)" 8
911 Joins the separate strings of LIST or ARRAY into a single string with fields
912 separated by the value of EXPR, and returns the string.
913 Example:
914 .nf
915     
916 .ie t \{\
917     $_ = join(\|\':\', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
918 'br\}
919 .el \{\
920     $_ = join(\|\':\',
921                 $login,$passwd,$uid,$gid,$gcos,$home,$shell);
922 'br\}
923
924 .fi
925 See
926 .IR split .
927 .Ip "keys(ASSOC_ARRAY)" 8 6
928 .Ip "keys ASSOC_ARRAY" 8
929 Returns a normal array consisting of all the keys of the named associative
930 array.
931 The keys are returned in an apparently random order, but it is the same order
932 as either the values() or each() function produces (given that the associative array
933 has not been modified).
934 Here is yet another way to print your environment:
935 .nf
936
937 .ne 5
938         @keys = keys %ENV;
939         @values = values %ENV;
940         while ($#keys >= 0) {
941                 print pop(keys), \'=\', pop(values), "\en";
942         }
943
944 or how about sorted by key:
945
946 .ne 3
947         foreach $key (sort(keys %ENV)) {
948                 print $key, \'=\', $ENV{$key}, "\en";
949         }
950
951 .fi
952 .Ip "kill(LIST)" 8 8
953 .Ip "kill LIST" 8 2
954 Sends a signal to a list of processes.
955 The first element of the list must be the signal to send.
956 Returns the number of processes successfully signaled.
957 .nf
958
959         $cnt = kill 1, $child1, $child2;
960         kill 9, @goners;
961
962 .fi
963 If the signal is negative, kills process groups instead of processes.
964 (On System V, a negative \fIprocess\fR number will also kill process groups,
965 but that's not portable.)
966 You may use a signal name in quotes.
967 .Ip "last LABEL" 8 8
968 .Ip "last" 8
969 The
970 .I last
971 command is like the
972 .I break
973 statement in C (as used in loops); it immediately exits the loop in question.
974 If the LABEL is omitted, the command refers to the innermost enclosing loop.
975 The
976 .I continue
977 block, if any, is not executed:
978 .nf
979
980 .ne 4
981         line: while (<STDIN>) {
982                 last line if /\|^$/;    # exit when done with header
983                 .\|.\|.
984         }
985
986 .fi
987 .Ip "length(EXPR)" 8 4
988 .Ip "length EXPR" 8
989 Returns the length in characters of the value of EXPR.
990 If EXPR is omitted, returns length of $_.
991 .Ip "link(OLDFILE,NEWFILE)" 8 2
992 Creates a new filename linked to the old filename.
993 Returns 1 for success, 0 otherwise.
994 .Ip "listen(SOCKET,QUEUESIZE)" 8 2
995 Does the same thing that the listen system call does.
996 Returns true if it succeeded, false otherwise.
997 See example in section on Interprocess Communication.
998 .Ip "local(LIST)" 8 4
999 Declares the listed variables to be local to the enclosing block,
1000 subroutine, eval or \*(L"do\*(R".
1001 All the listed elements must be legal lvalues.
1002 This operator works by saving the current values of those variables in LIST
1003 on a hidden stack and restoring them upon exiting the block, subroutine or eval.
1004 This means that called subroutines can also reference the local variable,
1005 but not the global one.
1006 The LIST may be assigned to if desired, which allows you to initialize
1007 your local variables.
1008 (If no initializer is given for a particular variable, it is created with
1009 an undefined value.)
1010 Commonly this is used to name the parameters to a subroutine.
1011 Examples:
1012 .nf
1013
1014 .ne 13
1015         sub RANGEVAL {
1016                 local($min, $max, $thunk) = @_;
1017                 local($result) = \'\';
1018                 local($i);
1019
1020                 # Presumably $thunk makes reference to $i
1021
1022                 for ($i = $min; $i < $max; $i++) {
1023                         $result .= eval $thunk;
1024                 }
1025
1026                 $result;
1027         }
1028
1029 .ne 6
1030         if ($sw eq \'-v\') {
1031             # init local array with global array
1032             local(@ARGV) = @ARGV;
1033             unshift(@ARGV,\'echo\');
1034             system @ARGV;
1035         }
1036         # @ARGV restored
1037
1038 .ne 6
1039         # temporarily add to digits associative array
1040         if ($base12) {
1041                 # (NOTE: not claiming this is efficient!)
1042                 local(%digits) = (%digits,'t',10,'e',11);
1043                 do parse_num();
1044         }
1045
1046 .fi
1047 Note that local() is a run-time command, and so gets executed every time
1048 through a loop, using up more stack storage each time until it's all
1049 released at once when the loop is exited.
1050 .Ip "localtime(EXPR)" 8 4
1051 .Ip "localtime EXPR" 8
1052 Converts a time as returned by the time function to a 9-element array with
1053 the time analyzed for the local timezone.
1054 Typically used as follows:
1055 .nf
1056
1057 .ne 3
1058 .ie t \{\
1059     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
1060 'br\}
1061 .el \{\
1062     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1063                                                 localtime(time);
1064 'br\}
1065
1066 .fi
1067 All array elements are numeric, and come straight out of a struct tm.
1068 In particular this means that $mon has the range 0.\|.11 and $wday has the
1069 range 0.\|.6.
1070 If EXPR is omitted, does localtime(time).
1071 .Ip "log(EXPR)" 8 4
1072 .Ip "log EXPR" 8
1073 Returns logarithm (base
1074 .IR e )
1075 of EXPR.
1076 If EXPR is omitted, returns log of $_.
1077 .Ip "lstat(FILEHANDLE)" 8 6
1078 .Ip "lstat FILEHANDLE" 8
1079 .Ip "lstat(EXPR)" 8
1080 .Ip "lstat SCALARVARIABLE" 8
1081 Does the same thing as the stat() function, but stats a symbolic link
1082 instead of the file the symbolic link points to.
1083 If symbolic links are unimplemented on your system, a normal stat is done.
1084 .Ip "m/PATTERN/io" 8 4
1085 .Ip "/PATTERN/io" 8
1086 Searches a string for a pattern match, and returns true (1) or false (\'\').
1087 If no string is specified via the =~ or !~ operator,
1088 the $_ string is searched.
1089 (The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
1090 See also the section on regular expressions.
1091 .Sp
1092 If / is the delimiter then the initial \*(L'm\*(R' is optional.
1093 With the \*(L'm\*(R' you can use any pair of non-alphanumeric characters
1094 as delimiters.
1095 This is particularly useful for matching Unix path names that contain \*(L'/\*(R'.
1096 If the final delimiter is followed by the optional letter \*(L'i\*(R', the matching is
1097 done in a case-insensitive manner.
1098 PATTERN may contain references to scalar variables, which will be interpolated
1099 (and the pattern recompiled) every time the pattern search is evaluated.
1100 (Note that $) and $| may not be interpolated because they look like end-of-string tests.)
1101 If you want such a pattern to be compiled only once, add an \*(L"o\*(R" after
1102 the trailing delimiter.
1103 This avoids expensive run-time recompilations, and
1104 is useful when the value you are interpolating won't change over the
1105 life of the script.
1106 .Sp
1107 If used in a context that requires an array value, a pattern match returns an
1108 array consisting of the subexpressions matched by the parentheses in the
1109 pattern,
1110 i.e. ($1, $2, $3.\|.\|.).
1111 It does NOT actually set $1, $2, etc. in this case, nor does it set $+, $`, $&
1112 or $'.
1113 If the match fails, a null array is returned.
1114 If the match succeeds, but there were no parentheses, an array value of (1)
1115 is returned.
1116 .Sp
1117 Examples:
1118 .nf
1119
1120 .ne 4
1121     open(tty, \'/dev/tty\');
1122     <tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|);   # do foo if desired
1123
1124     if (/Version: \|*\|([0\-9.]*\|)\|/\|) { $version = $1; }
1125
1126     next if m#^/usr/spool/uucp#;
1127
1128 .ne 5
1129     # poor man's grep
1130     $arg = shift;
1131     while (<>) {
1132             print if /$arg/o;   # compile only once
1133     }
1134
1135     if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/))
1136
1137 .fi
1138 This last example splits $foo into the first two words and the remainder
1139 of the line, and assigns those three fields to $F1, $F2 and $Etc.
1140 The conditional is true if any variables were assigned, i.e. if the pattern
1141 matched.
1142 .Ip "mkdir(FILENAME,MODE)" 8 3
1143 Creates the directory specified by FILENAME, with permissions specified by
1144 MODE (as modified by umask).
1145 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
1146 .Ip "msgctl(ID,CMD,ARG)" 8 4
1147 Calls the System V IPC function msgctl.  If CMD is &IPC_STAT, then ARG
1148 must be a variable which will hold the returned msqid_ds structure.
1149 Returns like ioctl: the undefined value for error, "0 but true" for
1150 zero, or the actual return value otherwise.
1151 .Ip "msgget(KEY,FLAGS)" 8 4
1152 Calls the System V IPC function msgget.  Returns the message queue id,
1153 or the undefined value if there is an error.
1154 .Ip "msgsnd(ID,MSG,FLAGS)" 8 4
1155 Calls the System V IPC function msgsnd to send the message MSG to the
1156 message queue ID.  MSG must begin with the long integer message type,
1157 which may be created with pack("L", $type).  Returns true if
1158 successful, or false if there is an error.
1159 .Ip "msgrcv(ID,VAR,SIZE,TYPE,FLAGS)" 8 4
1160 Calls the System V IPC function msgrcv to receive a message from
1161 message queue ID into variable VAR with a maximum message size of
1162 SIZE.  Note that if a message is received, the message type will be
1163 the first thing in VAR, and the maximum length of VAR is SIZE plus the
1164 size of the message type.  Returns true if successful, or false if
1165 there is an error.