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