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