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