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