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