perl 3.0 patch #16 (combined patch)
[p5sagit/p5-mst-13.2.git] / perl.man.3
1 ''' Beginning of part 3
2 ''' $Header: perl.man.3,v 3.0.1.5 90/03/12 16:52:21 lwall Locked $
3 '''
4 ''' $Log:       perl.man.3,v $
5 ''' Revision 3.0.1.5  90/03/12  16:52:21  lwall
6 ''' patch13: documented that print $filehandle &foo is ambiguous
7 ''' patch13: added splice operator: @oldelems = splice(@array,$offset,$len,LIST)
8 ''' 
9 ''' Revision 3.0.1.4  90/02/28  18:00:09  lwall
10 ''' patch9: added pipe function
11 ''' patch9: documented how to handle arbitrary weird characters in filenames
12 ''' patch9: documented the unflushed buffers problem on piped opens
13 ''' patch9: documented how to force top of page
14 ''' 
15 ''' Revision 3.0.1.3  89/12/21  20:10:12  lwall
16 ''' patch7: documented that s`pat`repl` does command substitution on replacement
17 ''' patch7: documented that $timeleft from select() is likely not implemented
18 ''' 
19 ''' Revision 3.0.1.2  89/11/17  15:31:05  lwall
20 ''' patch5: fixed some manual typos and indent problems
21 ''' patch5: added warning about print making an array context
22 ''' 
23 ''' Revision 3.0.1.1  89/11/11  04:45:06  lwall
24 ''' patch2: made some line breaks depend on troff vs. nroff
25 ''' 
26 ''' Revision 3.0  89/10/18  15:21:46  lwall
27 ''' 3.0 baseline
28 ''' 
29 .Ip "next LABEL" 8 8
30 .Ip "next" 8
31 The
32 .I next
33 command is like the
34 .I continue
35 statement in C; it starts the next iteration of the loop:
36 .nf
37
38 .ne 4
39         line: while (<STDIN>) {
40                 next line if /\|^#/;    # discard comments
41                 .\|.\|.
42         }
43
44 .fi
45 Note that if there were a
46 .I continue
47 block on the above, it would get executed even on discarded lines.
48 If the LABEL is omitted, the command refers to the innermost enclosing loop.
49 .Ip "oct(EXPR)" 8 4
50 .Ip "oct EXPR" 8
51 Returns the decimal value of EXPR interpreted as an octal string.
52 (If EXPR happens to start off with 0x, interprets it as a hex string instead.)
53 The following will handle decimal, octal and hex in the standard notation:
54 .nf
55
56         $val = oct($val) if $val =~ /^0/;
57
58 .fi
59 If EXPR is omitted, uses $_.
60 .Ip "open(FILEHANDLE,EXPR)" 8 8
61 .Ip "open(FILEHANDLE)" 8
62 .Ip "open FILEHANDLE" 8
63 Opens the file whose filename is given by EXPR, and associates it with
64 FILEHANDLE.
65 If FILEHANDLE is an expression, its value is used as the name of the
66 real filehandle wanted.
67 If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
68 contains the filename.
69 If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
70 input.
71 If the filename begins with \*(L">\*(R", the file is opened for output.
72 If the filename begins with \*(L">>\*(R", the file is opened for appending.
73 (You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
74 want both read and write access to the file.)
75 If the filename begins with \*(L"|\*(R", the filename is interpreted
76 as a command to which output is to be piped, and if the filename ends
77 with a \*(L"|\*(R", the filename is interpreted as command which pipes
78 input to us.
79 (You may not have a command that pipes both in and out.)
80 Opening \'\-\' opens
81 .I STDIN
82 and opening \'>\-\' opens
83 .IR STDOUT .
84 Open returns non-zero upon success, the undefined value otherwise.
85 If the open involved a pipe, the return value happens to be the pid
86 of the subprocess.
87 Examples:
88 .nf
89     
90 .ne 3
91         $article = 100;
92         open article || die "Can't find article $article: $!\en";
93         while (<article>) {\|.\|.\|.
94
95 .ie t \{\
96         open(LOG, \'>>/usr/spool/news/twitlog\'\|);     # (log is reserved)
97 'br\}
98 .el \{\
99         open(LOG, \'>>/usr/spool/news/twitlog\'\|);
100                                         # (log is reserved)
101 'br\}
102
103 .ie t \{\
104         open(article, "caesar <$article |"\|);          # decrypt article
105 'br\}
106 .el \{\
107         open(article, "caesar <$article |"\|);
108                                         # decrypt article
109 'br\}
110
111 .ie t \{\
112         open(extract, "|sort >/tmp/Tmp$$"\|);           # $$ is our process#
113 'br\}
114 .el \{\
115         open(extract, "|sort >/tmp/Tmp$$"\|);
116                                         # $$ is our process#
117 'br\}
118
119 .ne 7
120         # process argument list of files along with any includes
121
122         foreach $file (@ARGV) {
123                 do process($file, \'fh00\');    # no pun intended
124         }
125
126         sub process {
127                 local($filename, $input) = @_;
128                 $input++;               # this is a string increment
129                 unless (open($input, $filename)) {
130                         print STDERR "Can't open $filename: $!\en";
131                         return;
132                 }
133 .ie t \{\
134                 while (<$input>) {              # note the use of indirection
135 'br\}
136 .el \{\
137                 while (<$input>) {              # note use of indirection
138 'br\}
139                         if (/^#include "(.*)"/) {
140                                 do process($1, $input);
141                                 next;
142                         }
143                         .\|.\|.         # whatever
144                 }
145         }
146
147 .fi
148 You may also, in the Bourne shell tradition, specify an EXPR beginning
149 with \*(L">&\*(R", in which case the rest of the string
150 is interpreted as the name of a filehandle
151 (or file descriptor, if numeric) which is to be duped and opened.
152 You may use & after >, >>, <, +>, +>> and +<.
153 The mode you specify should match the mode of the original filehandle.
154 Here is a script that saves, redirects, and restores
155 .I STDOUT
156 and
157 .IR STDERR :
158 .nf
159
160 .ne 21
161         #!/usr/bin/perl
162         open(SAVEOUT, ">&STDOUT");
163         open(SAVEERR, ">&STDERR");
164
165         open(STDOUT, ">foo.out") || die "Can't redirect stdout";
166         open(STDERR, ">&STDOUT") || die "Can't dup stdout";
167
168         select(STDERR); $| = 1;         # make unbuffered
169         select(STDOUT); $| = 1;         # make unbuffered
170
171         print STDOUT "stdout 1\en";     # this works for
172         print STDERR "stderr 1\en";     # subprocesses too
173
174         close(STDOUT);
175         close(STDERR);
176
177         open(STDOUT, ">&SAVEOUT");
178         open(STDERR, ">&SAVEERR");
179
180         print STDOUT "stdout 2\en";
181         print STDERR "stderr 2\en";
182
183 .fi
184 If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
185 then there is an implicit fork done, and the return value of open
186 is the pid of the child within the parent process, and 0 within the child
187 process.
188 (Use defined($pid) to determine if the open was successful.)
189 The filehandle behaves normally for the parent, but i/o to that
190 filehandle is piped from/to the
191 .IR STDOUT / STDIN
192 of the child process.
193 In the child process the filehandle isn't opened\*(--i/o happens from/to
194 the new
195 .I STDOUT
196 or
197 .IR STDIN .
198 Typically this is used like the normal piped open when you want to exercise
199 more control over just how the pipe command gets executed, such as when
200 you are running setuid, and don't want to have to scan shell commands
201 for metacharacters.
202 The following pairs are equivalent:
203 .nf
204
205 .ne 5
206         open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
207         open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
208
209         open(FOO, "cat \-n $file|");
210         open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
211
212 .fi
213 Explicitly closing any piped filehandle causes the parent process to wait for the
214 child to finish, and returns the status value in $?.
215 Note: on any operation which may do a fork,
216 unflushed buffers remain unflushed in both
217 processes, which means you may need to set $| to
218 avoid duplicate output.
219 .Sp
220 The filename that is passed to open will have leading and trailing
221 whitespace deleted.
222 In order to open a file with arbitrary weird characters in it, it's necessary
223 to protect any leading and trailing whitespace thusly:
224 .nf
225
226 .ne 2
227         $file =~ s#^(\es)#./$1#;
228         open(FOO, "< $file\e0");
229
230 .fi
231 .Ip "opendir(DIRHANDLE,EXPR)" 8 3
232 Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
233 rewinddir() and closedir().
234 Returns true if successful.
235 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
236 .Ip "ord(EXPR)" 8 4
237 .Ip "ord EXPR" 8
238 Returns the ascii value of the first character of EXPR.
239 If EXPR is omitted, uses $_.
240 .Ip "pack(TEMPLATE,LIST)" 8 4
241 Takes an array or list of values and packs it into a binary structure,
242 returning the string containing the structure.
243 The TEMPLATE is a sequence of characters that give the order and type
244 of values, as follows:
245 .nf
246
247         A       An ascii string, will be space padded.
248         a       An ascii string, will be null padded.
249         c       A native char value.
250         C       An unsigned char value.
251         s       A signed short value.
252         S       An unsigned short value.
253         i       A signed integer value.
254         I       An unsigned integer value.
255         l       A signed long value.
256         L       An unsigned long value.
257         n       A short in \*(L"network\*(R" order.
258         N       A long in \*(L"network\*(R" order.
259         p       A pointer to a string.
260         x       A null byte.
261
262 .fi
263 Each letter may optionally be followed by a number which gives a repeat
264 count.
265 With all types except "a" and "A" the pack function will gobble up that many values
266 from the LIST.
267 The "a" and "A" types gobble just one value, but pack it as a string that long,
268 padding with nulls or spaces as necessary.
269 (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
270 Examples:
271 .nf
272
273         $foo = pack("cccc",65,66,67,68);
274         # foo eq "ABCD"
275         $foo = pack("c4",65,66,67,68);
276         # same thing
277
278         $foo = pack("ccxxcc",65,66,67,68);
279         # foo eq "AB\e0\e0CD"
280
281         $foo = pack("s2",1,2);
282         # "\e1\e0\e2\e0" on little-endian
283         # "\e0\e1\e0\e2" on big-endian
284
285         $foo = pack("a4","abcd","x","y","z");
286         # "abcd"
287
288         $foo = pack("aaaa","abcd","x","y","z");
289         # "axyz"
290
291         $foo = pack("a14","abcdefg");
292         # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
293
294         $foo = pack("i9pl", gmtime);
295         # a real struct tm (on my system anyway)
296
297 .fi
298 The same template may generally also be used in the unpack function.
299 .Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
300 Opens a pair of connected pipes like the corresponding system call.
301 Note that if you set up a loop of piped processes, deadlock can occur
302 unless you are very careful.
303 In addition, note that perl's pipes use stdio buffering, so you may need
304 to set $| to flush your WRITEHANDLE after each command, depending on
305 the application.
306 [Requires version 3.0 patchlevel 9.]
307 .Ip "pop(ARRAY)" 8
308 .Ip "pop ARRAY" 8 6
309 Pops and returns the last value of the array, shortening the array by 1.
310 Has the same effect as
311 .nf
312
313         $tmp = $ARRAY[$#ARRAY\-\|\-];
314
315 .fi
316 If there are no elements in the array, returns the undefined value.
317 .Ip "print(FILEHANDLE LIST)" 8 10
318 .Ip "print(LIST)" 8
319 .Ip "print FILEHANDLE LIST" 8
320 .Ip "print LIST" 8
321 .Ip "print" 8
322 Prints a string or a comma-separated list of strings.
323 Returns non-zero if successful.
324 FILEHANDLE may be a scalar variable name, in which case the variable contains
325 the name of the filehandle, thus introducing one level of indirection.
326 (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
327 misinterpreted as an operator unless you interpose a + or put parens around
328 the arguments.)
329 If FILEHANDLE is omitted, prints by default to standard output (or to the
330 last selected output channel\*(--see select()).
331 If LIST is also omitted, prints $_ to
332 .IR STDOUT .
333 To set the default output channel to something other than
334 .I STDOUT
335 use the select operation.
336 Note that, because print takes a LIST, anything in the LIST is evaluated
337 in an array context, and any subroutine that you call will have one or more
338 of its expressions evaluated in an array context.
339 Also be careful not to follow the print keyword with a left parenthesis
340 unless you want the corresponding right parenthesis to terminate the
341 arguments to the print--interpose a + or put parens around all the arguments.
342 .Ip "printf(FILEHANDLE LIST)" 8 10
343 .Ip "printf(LIST)" 8
344 .Ip "printf FILEHANDLE LIST" 8
345 .Ip "printf LIST" 8
346 Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
347 .Ip "push(ARRAY,LIST)" 8 7
348 Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
349 onto the end of ARRAY.
350 The length of ARRAY increases by the length of LIST.
351 Has the same effect as
352 .nf
353
354     for $value (LIST) {
355             $ARRAY[++$#ARRAY] = $value;
356     }
357
358 .fi
359 but is more efficient.
360 .Ip "q/STRING/" 8 5
361 .Ip "qq/STRING/" 8
362 These are not really functions, but simply syntactic sugar to let you
363 avoid putting too many backslashes into quoted strings.
364 The q operator is a generalized single quote, and the qq operator a
365 generalized double quote.
366 Any delimiter can be used in place of /, including newline.
367 If the delimiter is an opening bracket or parenthesis, the final delimiter
368 will be the corresponding closing bracket or parenthesis.
369 (Embedded occurrences of the closing bracket need to be backslashed as usual.)
370 Examples:
371 .nf
372
373 .ne 5
374         $foo = q!I said, "You said, \'She said it.\'"!;
375         $bar = q(\'This is it.\');
376         $_ .= qq
377 *** The previous line contains the naughty word "$&".\en
378                 if /(ibm|apple|awk)/;      # :-)
379
380 .fi
381 .Ip "rand(EXPR)" 8 8
382 .Ip "rand EXPR" 8
383 .Ip "rand" 8
384 Returns a random fractional number between 0 and the value of EXPR.
385 (EXPR should be positive.)
386 If EXPR is omitted, returns a value between 0 and 1.
387 See also srand().
388 .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
389 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
390 FILEHANDLE.
391 Returns the number of bytes actually read.
392 SCALAR will be grown or shrunk to the length actually read.
393 .Ip "readdir(DIRHANDLE)" 8 3
394 .Ip "readdir DIRHANDLE" 8
395 Returns the next directory entry for a directory opened by opendir().
396 If used in an array context, returns all the rest of the entries in the
397 directory.
398 If there are no more entries, returns an undefined value in a scalar context
399 or a null list in an array context.
400 .Ip "readlink(EXPR)" 8 6
401 .Ip "readlink EXPR" 8
402 Returns the value of a symbolic link, if symbolic links are implemented.
403 If not, gives a fatal error.
404 If there is some system error, returns the undefined value and sets $! (errno).
405 If EXPR is omitted, uses $_.
406 .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
407 Receives a message on a socket.
408 Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
409 SOCKET filehandle.
410 Returns the address of the sender, or the undefined value if there's an error.
411 SCALAR will be grown or shrunk to the length actually read.
412 Takes the same flags as the system call of the same name.
413 .Ip "redo LABEL" 8 8
414 .Ip "redo" 8
415 The
416 .I redo
417 command restarts the loop block without evaluating the conditional again.
418 The
419 .I continue
420 block, if any, is not executed.
421 If the LABEL is omitted, the command refers to the innermost enclosing loop.
422 This command is normally used by programs that want to lie to themselves
423 about what was just input:
424 .nf
425
426 .ne 16
427         # a simpleminded Pascal comment stripper
428         # (warning: assumes no { or } in strings)
429         line: while (<STDIN>) {
430                 while (s|\|({.*}.*\|){.*}|$1 \||) {}
431                 s|{.*}| \||;
432                 if (s|{.*| \||) {
433                         $front = $_;
434                         while (<STDIN>) {
435                                 if (\|/\|}/\|) {        # end of comment?
436                                         s|^|$front{|;
437                                         redo line;
438                                 }
439                         }
440                 }
441                 print;
442         }
443
444 .fi
445 .Ip "rename(OLDNAME,NEWNAME)" 8 2
446 Changes the name of a file.
447 Returns 1 for success, 0 otherwise.
448 Will not work across filesystem boundaries.
449 .Ip "reset(EXPR)" 8 6
450 .Ip "reset EXPR" 8
451 .Ip "reset" 8
452 Generally used in a
453 .I continue
454 block at the end of a loop to clear variables and reset ?? searches
455 so that they work again.
456 The expression is interpreted as a list of single characters (hyphens allowed
457 for ranges).
458 All variables and arrays beginning with one of those letters are reset to
459 their pristine state.
460 If the expression is omitted, one-match searches (?pattern?) are reset to
461 match again.
462 Only resets variables or searches in the current package.
463 Always returns 1.
464 Examples:
465 .nf
466
467 .ne 3
468     reset \'X\';        \h'|2i'# reset all X variables
469     reset \'a\-z\';\h'|2i'# reset lower case variables
470     reset;      \h'|2i'# just reset ?? searches
471
472 .fi
473 Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
474 arrays.
475 .Sp
476 The use of reset on dbm associative arrays does not change the dbm file.
477 (It does, however, flush any entries cached by perl, which may be useful if
478 you are sharing the dbm file.
479 Then again, maybe not.)
480 .Ip "return LIST" 8 3
481 Returns from a subroutine with the value specified.
482 (Note that a subroutine can automatically return
483 the value of the last expression evaluated.
484 That's the preferred method\*(--use of an explicit
485 .I return
486 is a bit slower.)
487 .Ip "reverse(LIST)" 8 4
488 .Ip "reverse LIST" 8
489 Returns an array value consisting of the elements of LIST in the opposite order.
490 .Ip "rewinddir(DIRHANDLE)" 8 5
491 .Ip "rewinddir DIRHANDLE" 8
492 Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
493 .Ip "rindex(STR,SUBSTR)" 8 4
494 Works just like index except that it
495 returns the position of the LAST occurrence of SUBSTR in STR.
496 .Ip "rmdir(FILENAME)" 8 4
497 .Ip "rmdir FILENAME" 8
498 Deletes the directory specified by FILENAME if it is empty.
499 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
500 If FILENAME is omitted, uses $_.
501 .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
502 Searches a string for a pattern, and if found, replaces that pattern with the
503 replacement text and returns the number of substitutions made.
504 Otherwise it returns false (0).
505 The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
506 of the pattern are to be replaced.
507 The \*(L"i\*(R" is also optional, and if present, indicates that matching
508 is to be done in a case-insensitive manner.
509 The \*(L"e\*(R" is likewise optional, and if present, indicates that
510 the replacement string is to be evaluated as an expression rather than just
511 as a double-quoted string.
512 Any delimiter may replace the slashes; if single quotes are used, no
513 interpretation is done on the replacement string (the e modifier overrides
514 this, however); if backquotes are used, the replacement string is a command
515 to execute whose output will be used as the actual replacement text.
516 If no string is specified via the =~ or !~ operator,
517 the $_ string is searched and modified.
518 (The string specified with =~ must be a scalar variable, an array element,
519 or an assignment to one of those, i.e. an lvalue.)
520 If the pattern contains a $ that looks like a variable rather than an
521 end-of-string test, the variable will be interpolated into the pattern at
522 run-time.
523 If you only want the pattern compiled once the first time the variable is
524 interpolated, add an \*(L"o\*(R" at the end.
525 See also the section on regular expressions.
526 Examples:
527 .nf
528
529     s/\|\e\|bgreen\e\|b/mauve/g;                # don't change wintergreen
530
531     $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
532
533     s/Login: $foo/Login: $bar/; # run-time pattern
534
535     ($foo = $bar) =~ s/bar/foo/;
536
537     $_ = \'abc123xyz\';
538     s/\ed+/$&*2/e;              # yields \*(L'abc246xyz\*(R'
539     s/\ed+/sprintf("%5d",$&)/e; # yields \*(L'abc  246xyz\*(R'
540     s/\ew/$& x 2/eg;            # yields \*(L'aabbcc  224466xxyyzz\*(R'
541
542     s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;  # reverse 1st two fields
543
544 .fi
545 (Note the use of $ instead of \|\e\| in the last example.  See section
546 on regular expressions.)
547 .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
548 Randomly positions the file pointer for FILEHANDLE, just like the fseek()
549 call of stdio.
550 FILEHANDLE may be an expression whose value gives the name of the filehandle.
551 Returns 1 upon success, 0 otherwise.
552 .Ip "seekdir(DIRHANDLE,POS)" 8 3
553 Sets the current position for the readdir() routine on DIRHANDLE.
554 POS must be a value returned by seekdir().
555 Has the same caveats about possible directory compaction as the corresponding
556 system library routine.
557 .Ip "select(FILEHANDLE)" 8 3
558 .Ip "select" 8 3
559 Returns the currently selected filehandle.
560 Sets the current default filehandle for output, if FILEHANDLE is supplied.
561 This has two effects: first, a
562 .I write
563 or a
564 .I print
565 without a filehandle will default to this FILEHANDLE.
566 Second, references to variables related to output will refer to this output
567 channel.
568 For example, if you have to set the top of form format for more than
569 one output channel, you might do the following:
570 .nf
571
572 .ne 4
573         select(REPORT1);
574         $^ = \'report1_top\';
575         select(REPORT2);
576         $^ = \'report2_top\';
577
578 .fi
579 FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
580 Thus:
581 .nf
582
583         $oldfh = select(STDERR); $| = 1; select($oldfh);
584
585 .fi
586 .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
587 This calls the select system call with the bitmasks specified, which can
588 be constructed using fileno() and vec(), along these lines:
589 .nf
590
591         $rin = $win = $ein = '';
592         vec($rin,fileno(STDIN),1) = 1;
593         vec($win,fileno(STDOUT),1) = 1;
594         $ein = $rin | $win;
595
596 .fi
597 If you want to select on many filehandles you might wish to write a subroutine:
598 .nf
599
600         sub fhbits {
601             local(@fhlist) = split(' ',$_[0]);
602             local($bits);
603             for (@fhlist) {
604                 vec($bits,fileno($_),1) = 1;
605             }
606             $bits;
607         }
608         $rin = &fhbits('STDIN TTY SOCK');
609
610 .fi
611 The usual idiom is:
612 .nf
613
614         ($nfound,$timeleft) =
615           select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
616
617 or to block until something becomes ready:
618
619 .ie t \{\
620         $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
621 'br\}
622 .el \{\
623         $nfound = select($rout=$rin, $wout=$win,
624                                 $eout=$ein, undef);
625 'br\}
626
627 .fi
628 Any of the bitmasks can also be undef.
629 The timeout, if specified, is in seconds, which may be fractional.
630 NOTE: not all implementations are capable of returning the $timeleft.
631 If not, they always return $timeleft equal to the supplied $timeout.
632 .Ip "setpgrp(PID,PGRP)" 8 4
633 Sets the current process group for the specified PID, 0 for the current
634 process.
635 Will produce a fatal error if used on a machine that doesn't implement
636 setpgrp(2).
637 .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
638 .Ip "send(SOCKET,MSG,FLAGS)" 8
639 Sends a message on a socket.
640 Takes the same flags as the system call of the same name.
641 On unconnected sockets you must specify a destination to send TO.
642 Returns the number of characters sent, or the undefined value if
643 there is an error.
644 .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
645 Sets the current priority for a process, a process group, or a user.
646 (See setpriority(2).)
647 Will produce a fatal error if used on a machine that doesn't implement
648 setpriority(2).
649 .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
650 Sets the socket option requested.
651 Returns undefined if there is an error.
652 OPTVAL may be specified as undef if you don't want to pass an argument.
653 .Ip "shift(ARRAY)" 8 6
654 .Ip "shift ARRAY" 8
655 .Ip "shift" 8
656 Shifts the first value of the array off and returns it,
657 shortening the array by 1 and moving everything down.
658 If there are no elements in the array, returns the undefined value.
659 If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
660 array in subroutines.
661 See also unshift(), push() and pop().
662 Shift() and unshift() do the same thing to the left end of an array that push()
663 and pop() do to the right end.
664 .Ip "shutdown(SOCKET,HOW)" 8 3
665 Shuts down a socket connection in the manner indicated by HOW, which has
666 the same interpretation as in the system call of the same name.
667 .Ip "sin(EXPR)" 8 4
668 .Ip "sin EXPR" 8
669 Returns the sine of EXPR (expressed in radians).
670 If EXPR is omitted, returns sine of $_.
671 .Ip "sleep(EXPR)" 8 6
672 .Ip "sleep EXPR" 8
673 .Ip "sleep" 8
674 Causes the script to sleep for EXPR seconds, or forever if no EXPR.
675 May be interrupted by sending the process a SIGALARM.
676 Returns the number of seconds actually slept.
677 .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
678 Opens a socket of the specified kind and attaches it to filehandle SOCKET.
679 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
680 of the same name.
681 You may need to run makelib on sys/socket.h to get the proper values handy
682 in a perl library file.
683 Return true if successful.
684 See the example in the section on Interprocess Communication.
685 .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
686 Creates an unnamed pair of sockets in the specified domain, of the specified
687 type.
688 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
689 of the same name.
690 If unimplemented, yields a fatal error.
691 Return true if successful.
692 .Ip "sort(SUBROUTINE LIST)" 8 9
693 .Ip "sort(LIST)" 8
694 .Ip "sort SUBROUTINE LIST" 8
695 .Ip "sort LIST" 8
696 Sorts the LIST and returns the sorted array value.
697 Nonexistent values of arrays are stripped out.
698 If SUBROUTINE is omitted, sorts in standard string comparison order.
699 If SUBROUTINE is specified, gives the name of a subroutine that returns
700 an integer less than, equal to, or greater than 0,
701 depending on how the elements of the array are to be ordered.
702 In the interests of efficiency the normal calling code for subroutines
703 is bypassed, with the following effects: the subroutine may not be a recursive
704 subroutine, and the two elements to be compared are passed into the subroutine
705 not via @_ but as $a and $b (see example below).
706 They are passed by reference so don't modify $a and $b.
707 SUBROUTINE may be a scalar variable name, in which case the value provides
708 the name of the subroutine to use.
709 Examples:
710 .nf
711
712 .ne 4
713         sub byage {
714             $age{$a} - $age{$b};        # presuming integers
715         }
716         @sortedclass = sort byage @class;
717
718 .ne 9
719         sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
720         @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
721         @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
722         print sort @harry;
723                 # prints AbelCaincatdogx
724         print sort reverse @harry;
725                 # prints xdogcatCainAbel
726         print sort @george, \'to\', @harry;
727                 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
728
729 .fi
730 .Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
731 .Ip "splice(ARRAY,OFFSET,LENGTH)" 8
732 .Ip "splice(ARRAY,OFFSET)" 8
733 Removes the elements designated by OFFSET and LENGTH from an array, and
734 replaces them with the elements of LIST, if any.
735 Returns the elements removed from the array.
736 The array grows or shrinks as necessary.
737 If LENGTH is omitted, removes everything from OFFSET onward.
738 The following equivalencies hold (assuming $[ == 0):
739 .nf
740
741         push(@a,$x,$y)\h'|3.5i'splice(@a,$#x+1,0,$x,$y)
742         pop(@a)\h'|3.5i'splice(@a,-1)
743         shift(@a)\h'|3.5i'splice(@a,0,1)
744         unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
745         $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
746
747 Example, assuming array lengths are passed before arrays:
748         
749         sub aeq {       # compare two array values
750                 local(@a) = splice(@_,0,shift);
751                 local(@b) = splice(@_,0,shift);
752                 return 0 unless @a == @b;       # same len?
753                 while (@a) {
754                     return 0 if pop(@a) ne pop(@b);
755                 }
756                 return 1;
757         }
758         if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
759
760 .fi
761 .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
762 .Ip "split(/PATTERN/,EXPR)" 8 8
763 .Ip "split(/PATTERN/)" 8
764 .Ip "split" 8
765 Splits a string into an array of strings, and returns it.
766 (If not in an array context, returns the number of fields found and splits
767 into the @_ array.
768 (In an array context, you can force the split into @_
769 by using ?? as the pattern delimiters, but it still returns the array value.))
770 If EXPR is omitted, splits the $_ string.
771 If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
772 Anything matching PATTERN is taken to be a delimiter separating the fields.
773 (Note that the delimiter may be longer than one character.)
774 If LIMIT is specified, splits into no more than that many fields (though it
775 may split into fewer).
776 If LIMIT is unspecified, trailing null fields are stripped (which
777 potential users of pop() would do well to remember).
778 A pattern matching the null string (not to be confused with a null pattern,
779 which is one member of the set of patterns matching a null string)
780 will split the value of EXPR into separate characters at each point it
781 matches that way.
782 For example:
783 .nf
784
785         print join(\':\', split(/ */, \'hi there\'));
786
787 .fi
788 produces the output \*(L'h:i:t:h:e:r:e\*(R'.
789 .Sp
790 The LIMIT parameter can be used to partially split a line
791 .nf
792
793         ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
794
795 .fi
796 (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
797 larger than the number of variables in the list, to avoid unnecessary work.
798 For the list above LIMIT would have been 4 by default.
799 In time critical applications it behooves you not to split into
800 more fields than you really need.)
801 .Sp
802 If the PATTERN contains parentheses, additional array elements are created
803 from each matching substring in the delimiter.
804 .Sp
805         split(/([,-])/,"1-10,20");
806 .Sp
807 produces the array value
808 .Sp
809         (1,'-',10,',',20)
810 .Sp
811 The pattern /PATTERN/ may be replaced with an expression to specify patterns
812 that vary at runtime.
813 (To do runtime compilation only once, use /$variable/o.)
814 As a special case, specifying a space (\'\ \') will split on white space
815 just as split with no arguments does, but leading white space does NOT
816 produce a null first field.
817 Thus, split(\'\ \') can be used to emulate
818 .IR awk 's
819 default behavior, whereas
820 split(/\ /) will give you as many null initial fields as there are
821 leading spaces.
822 .Sp
823 Example:
824 .nf
825
826 .ne 5
827         open(passwd, \'/etc/passwd\');
828         while (<passwd>) {
829 .ie t \{\
830                 ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
831 'br\}
832 .el \{\
833                 ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
834                         = split(\|/\|:\|/\|);
835 'br\}
836                 .\|.\|.
837         }
838
839 .fi
840 (Note that $shell above will still have a newline on it.  See chop().)
841 See also
842 .IR join .
843 .Ip "sprintf(FORMAT,LIST)" 8 4
844 Returns a string formatted by the usual printf conventions.
845 The * character is not supported.
846 .Ip "sqrt(EXPR)" 8 4
847 .Ip "sqrt EXPR" 8
848 Return the square root of EXPR.
849 If EXPR is omitted, returns square root of $_.
850 .Ip "srand(EXPR)" 8 4
851 .Ip "srand EXPR" 8
852 Sets the random number seed for the
853 .I rand
854 operator.
855 If EXPR is omitted, does srand(time).
856 .Ip "stat(FILEHANDLE)" 8 8
857 .Ip "stat FILEHANDLE" 8
858 .Ip "stat(EXPR)" 8
859 .Ip "stat SCALARVARIABLE" 8
860 Returns a 13-element array giving the statistics for a file, either the file
861 opened via FILEHANDLE, or named by EXPR.
862 Typically used as follows:
863 .nf
864
865 .ne 3
866     ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
867        $atime,$mtime,$ctime,$blksize,$blocks)
868            = stat($filename);
869
870 .fi
871 If stat is passed the special filehandle consisting of an underline,
872 no stat is done, but the current contents of the stat structure from
873 the last stat or filetest are returned.
874 Example:
875 .nf
876
877 .ne 3
878         if (-x $file && (($d) = stat(_)) && $d < 0) {
879                 print "$file is executable NFS file\en";
880         }
881
882 .fi
883 .Ip "study(SCALAR)" 8 6
884 .Ip "study SCALAR" 8
885 .Ip "study"
886 Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
887 doing many pattern matches on the string before it is next modified.
888 This may or may not save time, depending on the nature and number of patterns
889 you are searching on, and on the distribution of character frequencies in
890 the string to be searched\*(--you probably want to compare runtimes with and
891 without it to see which runs faster.
892 Those loops which scan for many short constant strings (including the constant
893 parts of more complex patterns) will benefit most.
894 You may have only one study active at a time\*(--if you study a different
895 scalar the first is \*(L"unstudied\*(R".
896 (The way study works is this: a linked list of every character in the string
897 to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
898 are.
899 From each search string, the rarest character is selected, based on some
900 static frequency tables constructed from some C programs and English text.
901 Only those places that contain this \*(L"rarest\*(R" character are examined.)
902 .Sp
903 For example, here is a loop which inserts index producing entries before any line
904 containing a certain pattern:
905 .nf
906
907 .ne 8
908         while (<>) {
909                 study;
910                 print ".IX foo\en" if /\ebfoo\eb/;
911                 print ".IX bar\en" if /\ebbar\eb/;
912                 print ".IX blurfl\en" if /\ebblurfl\eb/;
913                 .\|.\|.
914                 print;
915         }
916
917 .fi
918 In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
919 will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
920 In general, this is a big win except in pathological cases.
921 The only question is whether it saves you more time than it took to build
922 the linked list in the first place.
923 .Sp
924 Note that if you have to look for strings that you don't know till runtime,
925 you can build an entire loop as a string and eval that to avoid recompiling
926 all your patterns all the time.
927 Together with setting $/ to input entire files as one record, this can
928 be very fast, often faster than specialized programs like fgrep.
929 The following scans a list of files (@files)
930 for a list of words (@words), and prints out the names of those files that
931 contain a match:
932 .nf
933
934 .ne 12
935         $search = \'while (<>) { study;\';
936         foreach $word (@words) {
937             $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
938         }
939         $search .= "}";
940         @ARGV = @files;
941         $/ = "\e177";           # something that doesn't occur
942         eval $search;           # this screams
943         $/ = "\en";             # put back to normal input delim
944         foreach $file (sort keys(%seen)) {
945             print $file, "\en";
946         }
947
948 .fi
949 .Ip "substr(EXPR,OFFSET,LEN)" 8 2
950 Extracts a substring out of EXPR and returns it.
951 First character is at offset 0, or whatever you've set $[ to.
952 If OFFSET is negative, starts that far from the end of the string.
953 You can use the substr() function as an lvalue, in which case EXPR must
954 be an lvalue.
955 If you assign something shorter than LEN, the string will shrink, and
956 if you assign something longer than LEN, the string will grow to accommodate it.
957 To keep the string the same length you may need to pad or chop your value using
958 sprintf().
959 .Ip "syscall(LIST)" 8 6
960 .Ip "syscall LIST" 8
961 Calls the system call specified as the first element of the list, passing
962 the remaining elements as arguments to the system call.
963 If unimplemented, produces a fatal error.
964 The arguments are interpreted as follows: if a given argument is numeric,
965 the argument is passed as an int.
966 If not, the pointer to the string value is passed.
967 You are responsible to make sure a string is pre-extended long enough
968 to receive any result that might be written into a string.
969 If your integer arguments are not literals and have never been interpreted
970 in a numeric context, you may need to add 0 to them to force them to look
971 like numbers.
972 .nf
973
974         do 'syscall.h';         # may need to run makelib
975         syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
976
977 .fi
978 .Ip "system(LIST)" 8 6
979 .Ip "system LIST" 8
980 Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
981 is done first, and the parent process waits for the child process to complete.
982 Note that argument processing varies depending on the number of arguments.
983 The return value is the exit status of the program as returned by the wait()
984 call.
985 To get the actual exit value divide by 256.
986 See also
987 .IR exec .
988 .Ip "symlink(OLDFILE,NEWFILE)" 8 2
989 Creates a new filename symbolically linked to the old filename.
990 Returns 1 for success, 0 otherwise.
991 On systems that don't support symbolic links, produces a fatal error at
992 run time.
993 To check for that, use eval:
994 .nf
995
996         $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
997
998 .fi
999 .Ip "tell(FILEHANDLE)" 8 6
1000 .Ip "tell FILEHANDLE" 8 6
1001 .Ip "tell" 8
1002 Returns the current file position for FILEHANDLE.
1003 FILEHANDLE may be an expression whose value gives the name of the actual
1004 filehandle.
1005 If FILEHANDLE is omitted, assumes the file last read.
1006 .Ip "telldir(DIRHANDLE)" 8 5
1007 .Ip "telldir DIRHANDLE" 8
1008 Returns the current position of the readdir() routines on DIRHANDLE.
1009 Value may be given to seekdir() to access a particular location in
1010 a directory.
1011 Has the same caveats about possible directory compaction as the corresponding
1012 system library routine.
1013 .Ip "time" 8 4
1014 Returns the number of non-leap seconds since January 1, 1970, UTC.
1015 Suitable for feeding to gmtime() and localtime().
1016 .Ip "times" 8 4
1017 Returns a four-element array giving the user and system times, in seconds, for this
1018 process and the children of this process.
1019 .Sp
1020     ($user,$system,$cuser,$csystem) = times;
1021 .Sp
1022 .Ip "tr/SEARCHLIST/REPLACEMENTLIST/" 8 5
1023 .Ip "y/SEARCHLIST/REPLACEMENTLIST/" 8
1024 Translates all occurrences of the characters found in the search list with
1025 the corresponding character in the replacement list.
1026 It returns the number of characters replaced.
1027 If no string is specified via the =~ or !~ operator,
1028 the $_ string is translated.
1029 (The string specified with =~ must be a scalar variable, an array element,
1030 or an assignment to one of those, i.e. an lvalue.)
1031 For
1032 .I sed
1033 devotees,
1034 .I y
1035 is provided as a synonym for
1036 .IR tr .
1037 Examples:
1038 .nf
1039
1040     $ARGV[1] \|=~ \|y/A\-Z/a\-z/;       \h'|3i'# canonicalize to lower case
1041
1042     $cnt = tr/*/*/;             \h'|3i'# count the stars in $_
1043
1044     ($HOST = $host) =~ tr/a\-z/A\-Z/;
1045
1046     y/\e001\-@[\-_{\-\e177/ /;  \h'|3i'# change non-alphas to space
1047
1048 .fi
1049 .Ip "umask(EXPR)" 8 4
1050 .Ip "umask EXPR" 8
1051 .Ip "umask" 8
1052 Sets the umask for the process and returns the old one.
1053 If EXPR is omitted, merely returns current umask.
1054 .Ip "undef(EXPR)" 8 6
1055 .Ip "undef EXPR" 8
1056 .Ip "undef" 8
1057 Undefines the value of EXPR, which must be an lvalue.
1058 Use only on a scalar value, an entire array, or a subroutine name (using &).
1059 (Undef will probably not do what you expect on most predefined variables or
1060 dbm array values.)
1061 Always returns the undefined value.
1062 You can omit the EXPR, in which case nothing is undefined, but you still
1063 get an undefined value that you could, for instance, return from a subroutine.
1064 Examples:
1065 .nf
1066
1067 .ne 6
1068         undef $foo;
1069         undef $bar{'blurfl'};
1070         undef @ary;
1071         undef %assoc;
1072         undef &mysub;
1073         return (wantarray ? () : undef) if $they_blew_it;
1074
1075 .fi
1076 .Ip "unlink(LIST)" 8 4
1077 .Ip "unlink LIST" 8
1078 Deletes a list of files.
1079 Returns the number of files successfully deleted.
1080 .nf
1081
1082 .ne 2
1083         $cnt = unlink \'a\', \'b\', \'c\';
1084         unlink @goners;
1085         unlink <*.bak>;
1086
1087 .fi
1088 Note: unlink will not delete directories unless you are superuser and the
1089 .B \-U
1090 flag is supplied to
1091 .IR perl .
1092 Even if these conditions are met, be warned that unlinking a directory
1093 can inflict damage on your filesystem.
1094 Use rmdir instead.
1095 .Ip "unpack(TEMPLATE,EXPR)" 8 4
1096 Unpack does the reverse of pack: it takes a string representing
1097 a structure and expands it out into an array value, returning the array
1098 value.
1099 The TEMPLATE has the same format as in the pack function.
1100 Here's a subroutine that does substring:
1101 .nf
1102
1103 .ne 4
1104         sub substr {
1105                 local($what,$where,$howmuch) = @_;
1106                 unpack("x$where a$howmuch", $what);
1107         }
1108
1109 .ne 3
1110 and then there's
1111
1112         sub ord { unpack("c",$_[0]); }
1113
1114 .fi
1115 .Ip "unshift(ARRAY,LIST)" 8 4
1116 Does the opposite of a
1117 .IR shift .
1118 Or the opposite of a
1119 .IR push ,
1120 depending on how you look at it.
1121 Prepends list to the front of the array, and returns the number of elements
1122 in the new array.
1123 .nf
1124
1125         unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
1126
1127 .fi
1128 .Ip "utime(LIST)" 8 2
1129 .Ip "utime LIST" 8 2
1130 Changes the access and modification times on each file of a list of files.
1131 The first two elements of the list must be the NUMERICAL access and
1132 modification times, in that order.
1133 Returns the number of files successfully changed.
1134 The inode modification time of each file is set to the current time.
1135 Example of a \*(L"touch\*(R" command:
1136 .nf
1137
1138 .ne 3
1139         #!/usr/bin/perl
1140         $now = time;
1141         utime $now, $now, @ARGV;
1142
1143 .fi
1144 .Ip "values(ASSOC_ARRAY)" 8 6
1145 .Ip "values ASSOC_ARRAY" 8
1146 Returns a normal array consisting of all the values of the named associative
1147 array.
1148 The values are returned in an apparently random order, but it is the same order
1149 as either the keys() or each() function would produce on the same array.
1150 See also keys() and each().
1151 .Ip "vec(EXPR,OFFSET,BITS)" 8 2
1152 Treats a string as a vector of unsigned integers, and returns the value
1153 of the bitfield specified.
1154 May also be assigned to.
1155 BITS must be a power of two from 1 to 32.
1156 .Sp
1157 Vectors created with vec() can also be manipulated with the logical operators
1158 |, & and ^,
1159 which will assume a bit vector operation is desired when both operands are
1160 strings.
1161 This interpretation is not enabled unless there is at least one vec() in
1162 your program, to protect older programs.
1163 .Ip "wait" 8 6
1164 Waits for a child process to terminate and returns the pid of the deceased
1165 process, or -1 if there are no child processes.
1166 The status is returned in $?.
1167 If you expected a child and didn't find it, you probably had a call to
1168 system, a close on a pipe, or backticks between the fork and the wait.
1169 These constructs also do a wait and may have harvested your child process.
1170 .Ip "wantarray" 8 4
1171 Returns true if the context of the currently executing subroutine
1172 is looking for an array value.
1173 Returns false if the context is looking for a scalar.
1174 .nf
1175
1176         return wantarray ? () : undef;
1177
1178 .fi
1179 .Ip "warn(LIST)" 8 4
1180 .Ip "warn LIST" 8
1181 Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
1182 .Ip "write(FILEHANDLE)" 8 6
1183 .Ip "write(EXPR)" 8
1184 .Ip "write" 8
1185 Writes a formatted record (possibly multi-line) to the specified file,
1186 using the format associated with that file.
1187 By default the format for a file is the one having the same name is the
1188 filehandle, but the format for the current output channel (see
1189 .IR select )
1190 may be set explicitly
1191 by assigning the name of the format to the $~ variable.
1192 .Sp
1193 Top of form processing is handled automatically:
1194 if there is insufficient room on the current page for the formatted 
1195 record, the page is advanced by writing a form feed,
1196 a special top-of-page format is used
1197 to format the new page header, and then the record is written.
1198 By default the top-of-page format is \*(L"top\*(R", but it
1199 may be set to the
1200 format of your choice by assigning the name to the $^ variable.
1201 The number of lines remaining on the current page is in variable $-, which
1202 can be set to 0 to force a new page.
1203 .Sp
1204 If FILEHANDLE is unspecified, output goes to the current default output channel,
1205 which starts out as
1206 .I STDOUT
1207 but may be changed by the
1208 .I select
1209 operator.
1210 If the FILEHANDLE is an EXPR, then the expression is evaluated and the
1211 resulting string is used to look up the name of the FILEHANDLE at run time.
1212 For more on formats, see the section on formats later on.
1213 .Sp
1214 Note that write is NOT the opposite of read.