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