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