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