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