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