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