perl 3.0 patch #14 patch #13, continued
[p5sagit/p5-mst-13.2.git] / perl.man.3
CommitLineData
a687059c 1''' Beginning of part 3
79a0689e 2''' $Header: perl.man.3,v 3.0.1.5 90/03/12 16:52:21 lwall Locked $
a687059c 3'''
4''' $Log: perl.man.3,v $
79a0689e 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'''
ac58e20f 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'''
663a0e37 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'''
ffed7fef 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'''
ae986130 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'''
a687059c 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
31The
32.I next
33command is like the
34.I continue
35statement 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
45Note that if there were a
46.I continue
47block on the above, it would get executed even on discarded lines.
48If the LABEL is omitted, the command refers to the innermost enclosing loop.
49.Ip "oct(EXPR)" 8 4
50.Ip "oct EXPR" 8
51Returns 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.)
53The following will handle decimal, octal and hex in the standard notation:
54.nf
55
56 $val = oct($val) if $val =~ /^0/;
57
58.fi
59If EXPR is omitted, uses $_.
60.Ip "open(FILEHANDLE,EXPR)" 8 8
61.Ip "open(FILEHANDLE)" 8
62.Ip "open FILEHANDLE" 8
63Opens the file whose filename is given by EXPR, and associates it with
64FILEHANDLE.
65If FILEHANDLE is an expression, its value is used as the name of the
66real filehandle wanted.
67If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
68contains the filename.
69If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
70input.
71If the filename begins with \*(L">\*(R", the file is opened for output.
72If 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
74want both read and write access to the file.)
75If the filename begins with \*(L"|\*(R", the filename is interpreted
76as a command to which output is to be piped, and if the filename ends
77with a \*(L"|\*(R", the filename is interpreted as command which pipes
78input to us.
79(You may not have a command that pipes both in and out.)
80Opening \'\-\' opens
81.I STDIN
82and opening \'>\-\' opens
83.IR STDOUT .
84Open returns non-zero upon success, the undefined value otherwise.
85If the open involved a pipe, the return value happens to be the pid
86of the subprocess.
87Examples:
88.nf
89
90.ne 3
91 $article = 100;
92 open article || die "Can't find article $article: $!\en";
93 while (<article>) {\|.\|.\|.
94
ae986130 95.ie t \{\
a687059c 96 open(LOG, \'>>/usr/spool/news/twitlog\'\|); # (log is reserved)
ae986130 97'br\}
98.el \{\
99 open(LOG, \'>>/usr/spool/news/twitlog\'\|);
100 # (log is reserved)
101'br\}
a687059c 102
ae986130 103.ie t \{\
a687059c 104 open(article, "caesar <$article |"\|); # decrypt article
ae986130 105'br\}
106.el \{\
107 open(article, "caesar <$article |"\|);
108 # decrypt article
109'br\}
a687059c 110
ae986130 111.ie t \{\
a687059c 112 open(extract, "|sort >/tmp/Tmp$$"\|); # $$ is our process#
ae986130 113'br\}
114.el \{\
115 open(extract, "|sort >/tmp/Tmp$$"\|);
116 # $$ is our process#
117'br\}
a687059c 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 }
ae986130 133.ie t \{\
a687059c 134 while (<$input>) { # note the use of indirection
ae986130 135'br\}
136.el \{\
137 while (<$input>) { # note use of indirection
138'br\}
a687059c 139 if (/^#include "(.*)"/) {
140 do process($1, $input);
141 next;
142 }
143 .\|.\|. # whatever
144 }
145 }
146
147.fi
148You may also, in the Bourne shell tradition, specify an EXPR beginning
149with \*(L">&\*(R", in which case the rest of the string
150is interpreted as the name of a filehandle
151(or file descriptor, if numeric) which is to be duped and opened.
ae986130 152You may use & after >, >>, <, +>, +>> and +<.
153The mode you specify should match the mode of the original filehandle.
a687059c 154Here is a script that saves, redirects, and restores
155.I STDOUT
156and
ae986130 157.IR STDERR :
a687059c 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
184If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
185then there is an implicit fork done, and the return value of open
186is the pid of the child within the parent process, and 0 within the child
187process.
188(Use defined($pid) to determine if the open was successful.)
189The filehandle behaves normally for the parent, but i/o to that
190filehandle is piped from/to the
191.IR STDOUT / STDIN
192of the child process.
193In the child process the filehandle isn't opened\*(--i/o happens from/to
194the new
195.I STDOUT
196or
197.IR STDIN .
198Typically this is used like the normal piped open when you want to exercise
199more control over just how the pipe command gets executed, such as when
200you are running setuid, and don't want to have to scan shell commands
201for metacharacters.
202The 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
213Explicitly closing any piped filehandle causes the parent process to wait for the
214child to finish, and returns the status value in $?.
ac58e20f 215Note: on any operation which may do a fork,
216unflushed buffers remain unflushed in both
217processes, which means you may need to set $| to
218avoid duplicate output.
219.Sp
220The filename that is passed to open will have leading and trailing
221whitespace deleted.
222In order to open a file with arbitrary weird characters in it, it's necessary
223to 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
a687059c 231.Ip "opendir(DIRHANDLE,EXPR)" 8 3
232Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
233rewinddir() and closedir().
234Returns true if successful.
235DIRHANDLEs have their own namespace separate from FILEHANDLEs.
236.Ip "ord(EXPR)" 8 4
237.Ip "ord EXPR" 8
238Returns the ascii value of the first character of EXPR.
239If EXPR is omitted, uses $_.
240.Ip "pack(TEMPLATE,LIST)" 8 4
241Takes an array or list of values and packs it into a binary structure,
242returning the string containing the structure.
243The TEMPLATE is a sequence of characters that give the order and type
244of 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
263Each letter may optionally be followed by a number which gives a repeat
264count.
265With all types except "a" and "A" the pack function will gobble up that many values
266from the LIST.
267The "a" and "A" types gobble just one value, but pack it as a string that long,
268padding with nulls or spaces as necessary.
269(When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
270Examples:
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
ae986130 294 $foo = pack("i9pl", gmtime);
a687059c 295 # a real struct tm (on my system anyway)
296
297.fi
298The same template may generally also be used in the unpack function.
ac58e20f 299.Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
300Opens a pair of connected pipes like the corresponding system call.
301Note that if you set up a loop of piped processes, deadlock can occur
302unless you are very careful.
303In addition, note that perl's pipes use stdio buffering, so you may need
304to set $| to flush your WRITEHANDLE after each command, depending on
305the application.
306[Requires version 3.0 patchlevel 9.]
a687059c 307.Ip "pop(ARRAY)" 8
308.Ip "pop ARRAY" 8 6
309Pops and returns the last value of the array, shortening the array by 1.
310Has the same effect as
311.nf
312
313 $tmp = $ARRAY[$#ARRAY\-\|\-];
314
315.fi
316If 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
322Prints a string or a comma-separated list of strings.
323Returns non-zero if successful.
324FILEHANDLE may be a scalar variable name, in which case the variable contains
325the name of the filehandle, thus introducing one level of indirection.
79a0689e 326(NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
327misinterpreted as an operator unless you interpose a + or put parens around
328the arguments.)
a687059c 329If FILEHANDLE is omitted, prints by default to standard output (or to the
330last selected output channel\*(--see select()).
331If LIST is also omitted, prints $_ to
332.IR STDOUT .
333To set the default output channel to something other than
334.I STDOUT
335use the select operation.
ffed7fef 336Note that, because print takes a LIST, anything in the LIST is evaluated
337in an array context, and any subroutine that you call will have one or more
338of its expressions evaluated in an array context.
79a0689e 339Also be careful not to follow the print keyword with a left parenthesis
340unless you want the corresponding right parenthesis to terminate the
341arguments to the print--interpose a + or put parens around all the arguments.
a687059c 342.Ip "printf(FILEHANDLE LIST)" 8 10
343.Ip "printf(LIST)" 8
344.Ip "printf FILEHANDLE LIST" 8
345.Ip "printf LIST" 8
346Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
347.Ip "push(ARRAY,LIST)" 8 7
348Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
349onto the end of ARRAY.
350The length of ARRAY increases by the length of LIST.
351Has the same effect as
352.nf
353
354 for $value (LIST) {
355 $ARRAY[++$#ARRAY] = $value;
356 }
357
358.fi
359but is more efficient.
360.Ip "q/STRING/" 8 5
361.Ip "qq/STRING/" 8
362These are not really functions, but simply syntactic sugar to let you
363avoid putting too many backslashes into quoted strings.
364The q operator is a generalized single quote, and the qq operator a
365generalized double quote.
366Any delimiter can be used in place of /, including newline.
367If the delimiter is an opening bracket or parenthesis, the final delimiter
368will be the corresponding closing bracket or parenthesis.
369(Embedded occurrences of the closing bracket need to be backslashed as usual.)
370Examples:
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
384Returns a random fractional number between 0 and the value of EXPR.
385(EXPR should be positive.)
386If EXPR is omitted, returns a value between 0 and 1.
387See also srand().
388.Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
389Attempts to read LENGTH bytes of data into variable SCALAR from the specified
390FILEHANDLE.
391Returns the number of bytes actually read.
392SCALAR will be grown or shrunk to the length actually read.
393.Ip "readdir(DIRHANDLE)" 8 3
ae986130 394.Ip "readdir DIRHANDLE" 8
a687059c 395Returns the next directory entry for a directory opened by opendir().
396If used in an array context, returns all the rest of the entries in the
397directory.
398If there are no more entries, returns an undefined value in a scalar context
399or a null list in an array context.
400.Ip "readlink(EXPR)" 8 6
401.Ip "readlink EXPR" 8
402Returns the value of a symbolic link, if symbolic links are implemented.
403If not, gives a fatal error.
404If there is some system error, returns the undefined value and sets $! (errno).
405If EXPR is omitted, uses $_.
406.Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
407Receives a message on a socket.
408Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
409SOCKET filehandle.
410Returns the address of the sender, or the undefined value if there's an error.
411SCALAR will be grown or shrunk to the length actually read.
412Takes the same flags as the system call of the same name.
413.Ip "redo LABEL" 8 8
414.Ip "redo" 8
415The
416.I redo
417command restarts the loop block without evaluating the conditional again.
418The
419.I continue
420block, if any, is not executed.
421If the LABEL is omitted, the command refers to the innermost enclosing loop.
422This command is normally used by programs that want to lie to themselves
423about 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
446Changes the name of a file.
447Returns 1 for success, 0 otherwise.
448Will not work across filesystem boundaries.
449.Ip "reset(EXPR)" 8 6
450.Ip "reset EXPR" 8
451.Ip "reset" 8
452Generally used in a
453.I continue
454block at the end of a loop to clear variables and reset ?? searches
455so that they work again.
456The expression is interpreted as a list of single characters (hyphens allowed
457for ranges).
458All variables and arrays beginning with one of those letters are reset to
459their pristine state.
460If the expression is omitted, one-match searches (?pattern?) are reset to
461match again.
462Only resets variables or searches in the current package.
463Always returns 1.
464Examples:
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
473Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
474arrays.
475.Sp
476The 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
478you are sharing the dbm file.
479Then again, maybe not.)
480.Ip "return LIST" 8 3
481Returns from a subroutine with the value specified.
482(Note that a subroutine can automatically return
483the value of the last expression evaluated.
484That's the preferred method\*(--use of an explicit
485.I return
486is a bit slower.)
487.Ip "reverse(LIST)" 8 4
488.Ip "reverse LIST" 8
489Returns an array value consisting of the elements of LIST in the opposite order.
490.Ip "rewinddir(DIRHANDLE)" 8 5
491.Ip "rewinddir DIRHANDLE" 8
492Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
493.Ip "rindex(STR,SUBSTR)" 8 4
494Works just like index except that it
495returns the position of the LAST occurrence of SUBSTR in STR.
496.Ip "rmdir(FILENAME)" 8 4
497.Ip "rmdir FILENAME" 8
498Deletes the directory specified by FILENAME if it is empty.
499If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
500If FILENAME is omitted, uses $_.
501.Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
502Searches a string for a pattern, and if found, replaces that pattern with the
503replacement text and returns the number of substitutions made.
504Otherwise it returns false (0).
505The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
506of the pattern are to be replaced.
507The \*(L"i\*(R" is also optional, and if present, indicates that matching
508is to be done in a case-insensitive manner.
509The \*(L"e\*(R" is likewise optional, and if present, indicates that
510the replacement string is to be evaluated as an expression rather than just
511as a double-quoted string.
512Any delimiter may replace the slashes; if single quotes are used, no
513interpretation is done on the replacement string (the e modifier overrides
663a0e37 514this, however); if backquotes are used, the replacement string is a command
515to execute whose output will be used as the actual replacement text.
a687059c 516If no string is specified via the =~ or !~ operator,
517the $_ string is searched and modified.
518(The string specified with =~ must be a scalar variable, an array element,
519or an assignment to one of those, i.e. an lvalue.)
520If the pattern contains a $ that looks like a variable rather than an
521end-of-string test, the variable will be interpolated into the pattern at
522run-time.
523If you only want the pattern compiled once the first time the variable is
524interpolated, add an \*(L"o\*(R" at the end.
525See also the section on regular expressions.
526Examples:
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
546on regular expressions.)
547.Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
548Randomly positions the file pointer for FILEHANDLE, just like the fseek()
549call of stdio.
550FILEHANDLE may be an expression whose value gives the name of the filehandle.
551Returns 1 upon success, 0 otherwise.
552.Ip "seekdir(DIRHANDLE,POS)" 8 3
553Sets the current position for the readdir() routine on DIRHANDLE.
554POS must be a value returned by seekdir().
555Has the same caveats about possible directory compaction as the corresponding
556system library routine.
557.Ip "select(FILEHANDLE)" 8 3
558.Ip "select" 8 3
559Returns the currently selected filehandle.
560Sets the current default filehandle for output, if FILEHANDLE is supplied.
561This has two effects: first, a
562.I write
563or a
564.I print
565without a filehandle will default to this FILEHANDLE.
566Second, references to variables related to output will refer to this output
567channel.
568For example, if you have to set the top of form format for more than
569one 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
579FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
580Thus:
581.nf
582
583 $oldfh = select(STDERR); $| = 1; select($oldfh);
584
585.fi
586.Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
587This calls the select system call with the bitmasks specified, which can
588be 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
597If 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
611The usual idiom is:
612.nf
613
614 ($nfound,$timeleft) =
615 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
616
617or to block until something becomes ready:
618
ae986130 619.ie t \{\
a687059c 620 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
ae986130 621'br\}
622.el \{\
623 $nfound = select($rout=$rin, $wout=$win,
624 $eout=$ein, undef);
625'br\}
a687059c 626
627.fi
628Any of the bitmasks can also be undef.
629The timeout, if specified, is in seconds, which may be fractional.
663a0e37 630NOTE: not all implementations are capable of returning the $timeleft.
631If not, they always return $timeleft equal to the supplied $timeout.
a687059c 632.Ip "setpgrp(PID,PGRP)" 8 4
633Sets the current process group for the specified PID, 0 for the current
634process.
635Will produce a fatal error if used on a machine that doesn't implement
636setpgrp(2).
637.Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
638.Ip "send(SOCKET,MSG,FLAGS)" 8
639Sends a message on a socket.
640Takes the same flags as the system call of the same name.
641On unconnected sockets you must specify a destination to send TO.
642Returns the number of characters sent, or the undefined value if
643there is an error.
644.Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
645Sets the current priority for a process, a process group, or a user.
646(See setpriority(2).)
647Will produce a fatal error if used on a machine that doesn't implement
648setpriority(2).
649.Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
650Sets the socket option requested.
651Returns undefined if there is an error.
652OPTVAL 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
656Shifts the first value of the array off and returns it,
657shortening the array by 1 and moving everything down.
658If there are no elements in the array, returns the undefined value.
659If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
660array in subroutines.
661See also unshift(), push() and pop().
662Shift() and unshift() do the same thing to the left end of an array that push()
663and pop() do to the right end.
664.Ip "shutdown(SOCKET,HOW)" 8 3
665Shuts down a socket connection in the manner indicated by HOW, which has
666the same interpretation as in the system call of the same name.
667.Ip "sin(EXPR)" 8 4
668.Ip "sin EXPR" 8
669Returns the sine of EXPR (expressed in radians).
670If EXPR is omitted, returns sine of $_.
671.Ip "sleep(EXPR)" 8 6
672.Ip "sleep EXPR" 8
673.Ip "sleep" 8
674Causes the script to sleep for EXPR seconds, or forever if no EXPR.
675May be interrupted by sending the process a SIGALARM.
676Returns the number of seconds actually slept.
677.Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
678Opens a socket of the specified kind and attaches it to filehandle SOCKET.
679DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
680of the same name.
681You may need to run makelib on sys/socket.h to get the proper values handy
682in a perl library file.
683Return true if successful.
684See the example in the section on Interprocess Communication.
685.Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
686Creates an unnamed pair of sockets in the specified domain, of the specified
687type.
688DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
689of the same name.
690If unimplemented, yields a fatal error.
691Return 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
696Sorts the LIST and returns the sorted array value.
697Nonexistent values of arrays are stripped out.
698If SUBROUTINE is omitted, sorts in standard string comparison order.
699If SUBROUTINE is specified, gives the name of a subroutine that returns
700an integer less than, equal to, or greater than 0,
701depending on how the elements of the array are to be ordered.
702In the interests of efficiency the normal calling code for subroutines
703is bypassed, with the following effects: the subroutine may not be a recursive
704subroutine, and the two elements to be compared are passed into the subroutine
705not via @_ but as $a and $b (see example below).
706They are passed by reference so don't modify $a and $b.
707SUBROUTINE may be a scalar variable name, in which case the value provides
708the name of the subroutine to use.
709Examples:
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
79a0689e 730.Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
731.Ip "splice(ARRAY,OFFSET,LENGTH)" 8
732.Ip "splice(ARRAY,OFFSET)" 8
733Removes the elements designated by OFFSET and LENGTH from an array, and
734replaces them with the elements of LIST, if any.
735Returns the elements removed from the array.
736The array grows or shrinks as necessary.
737If LENGTH is omitted, removes everything from OFFSET onward.
738The 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
747Example, 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
a687059c 761.Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
762.Ip "split(/PATTERN/,EXPR)" 8 8
763.Ip "split(/PATTERN/)" 8
764.Ip "split" 8
765Splits 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
ac58e20f 767into the @_ array.
768(In an array context, you can force the split into @_
769by using ?? as the pattern delimiters, but it still returns the array value.))
a687059c 770If EXPR is omitted, splits the $_ string.
771If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
772Anything matching PATTERN is taken to be a delimiter separating the fields.
773(Note that the delimiter may be longer than one character.)
774If LIMIT is specified, splits into no more than that many fields (though it
775may split into fewer).
776If LIMIT is unspecified, trailing null fields are stripped (which
777potential users of pop() would do well to remember).
778A pattern matching the null string (not to be confused with a null pattern,
779which is one member of the set of patterns matching a null string)
780will split the value of EXPR into separate characters at each point it
781matches that way.
782For example:
783.nf
784
785 print join(\':\', split(/ */, \'hi there\'));
786
787.fi
788produces the output \*(L'h:i:t:h:e:r:e\*(R'.
ffed7fef 789.Sp
663a0e37 790The LIMIT parameter can be used to partially split a line
a687059c 791.nf
792
793 ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
794
795.fi
663a0e37 796(When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
a687059c 797larger than the number of variables in the list, to avoid unnecessary work.
663a0e37 798For the list above LIMIT would have been 4 by default.
a687059c 799In time critical applications it behooves you not to split into
800more fields than you really need.)
801.Sp
802If the PATTERN contains parentheses, additional array elements are created
803from each matching substring in the delimiter.
804.Sp
805 split(/([,-])/,"1-10,20");
806.Sp
807produces the array value
808.Sp
809 (1,'-',10,',',20)
810.Sp
811The pattern /PATTERN/ may be replaced with an expression to specify patterns
812that vary at runtime.
813(To do runtime compilation only once, use /$variable/o.)
814As a special case, specifying a space (\'\ \') will split on white space
815just as split with no arguments does, but leading white space does NOT
816produce a null first field.
817Thus, split(\'\ \') can be used to emulate
818.IR awk 's
819default behavior, whereas
820split(/\ /) will give you as many null initial fields as there are
821leading spaces.
822.Sp
823Example:
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().)
841See also
842.IR join .
843.Ip "sprintf(FORMAT,LIST)" 8 4
844Returns a string formatted by the usual printf conventions.
845The * character is not supported.
846.Ip "sqrt(EXPR)" 8 4
847.Ip "sqrt EXPR" 8
848Return the square root of EXPR.
849If EXPR is omitted, returns square root of $_.
850.Ip "srand(EXPR)" 8 4
851.Ip "srand EXPR" 8
852Sets the random number seed for the
853.I rand
854operator.
855If EXPR is omitted, does srand(time).
ae986130 856.Ip "stat(FILEHANDLE)" 8 8
a687059c 857.Ip "stat FILEHANDLE" 8
858.Ip "stat(EXPR)" 8
ae986130 859.Ip "stat SCALARVARIABLE" 8
a687059c 860Returns a 13-element array giving the statistics for a file, either the file
861opened via FILEHANDLE, or named by EXPR.
862Typically 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
871If stat is passed the special filehandle consisting of an underline,
872no stat is done, but the current contents of the stat structure from
873the last stat or filetest are returned.
874Example:
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"
886Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
887doing many pattern matches on the string before it is next modified.
888This may or may not save time, depending on the nature and number of patterns
889you are searching on, and on the distribution of character frequencies in
890the string to be searched\*(--you probably want to compare runtimes with and
891without it to see which runs faster.
892Those loops which scan for many short constant strings (including the constant
893parts of more complex patterns) will benefit most.
894You may have only one study active at a time\*(--if you study a different
895scalar the first is \*(L"unstudied\*(R".
896(The way study works is this: a linked list of every character in the string
897to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
898are.
899From each search string, the rarest character is selected, based on some
900static frequency tables constructed from some C programs and English text.
901Only those places that contain this \*(L"rarest\*(R" character are examined.)
902.Sp
903For example, here is a loop which inserts index producing entries before any line
904containing 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
918In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
919will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
920In general, this is a big win except in pathological cases.
921The only question is whether it saves you more time than it took to build
922the linked list in the first place.
923.Sp
924Note that if you have to look for strings that you don't know till runtime,
925you can build an entire loop as a string and eval that to avoid recompiling
926all your patterns all the time.
927Together with setting $/ to input entire files as one record, this can
928be very fast, often faster than specialized programs like fgrep.
929The following scans a list of files (@files)
930for a list of words (@words), and prints out the names of those files that
931contain 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
950Extracts a substring out of EXPR and returns it.
951First character is at offset 0, or whatever you've set $[ to.
952If OFFSET is negative, starts that far from the end of the string.
953You can use the substr() function as an lvalue, in which case EXPR must
954be an lvalue.
955If you assign something shorter than LEN, the string will shrink, and
ae986130 956if you assign something longer than LEN, the string will grow to accommodate it.
a687059c 957To keep the string the same length you may need to pad or chop your value using
958sprintf().
959.Ip "syscall(LIST)" 8 6
960.Ip "syscall LIST" 8
961Calls the system call specified as the first element of the list, passing
962the remaining elements as arguments to the system call.
963If unimplemented, produces a fatal error.
964The arguments are interpreted as follows: if a given argument is numeric,
965the argument is passed as an int.
966If not, the pointer to the string value is passed.
967You are responsible to make sure a string is pre-extended long enough
968to receive any result that might be written into a string.
969If your integer arguments are not literals and have never been interpreted
970in a numeric context, you may need to add 0 to them to force them to look
971like 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
980Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
981is done first, and the parent process waits for the child process to complete.
982Note that argument processing varies depending on the number of arguments.
983The return value is the exit status of the program as returned by the wait()
984call.
985To get the actual exit value divide by 256.
986See also
987.IR exec .
988.Ip "symlink(OLDFILE,NEWFILE)" 8 2
989Creates a new filename symbolically linked to the old filename.
990Returns 1 for success, 0 otherwise.
991On systems that don't support symbolic links, produces a fatal error at
992run time.
993To 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
1002Returns the current file position for FILEHANDLE.
1003FILEHANDLE may be an expression whose value gives the name of the actual
1004filehandle.
1005If FILEHANDLE is omitted, assumes the file last read.
1006.Ip "telldir(DIRHANDLE)" 8 5
1007.Ip "telldir DIRHANDLE" 8
1008Returns the current position of the readdir() routines on DIRHANDLE.
1009Value may be given to seekdir() to access a particular location in
1010a directory.
1011Has the same caveats about possible directory compaction as the corresponding
1012system library routine.
1013.Ip "time" 8 4
1014Returns the number of non-leap seconds since January 1, 1970, UTC.
1015Suitable for feeding to gmtime() and localtime().
1016.Ip "times" 8 4
1017Returns a four-element array giving the user and system times, in seconds, for this
1018process 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
1024Translates all occurrences of the characters found in the search list with
1025the corresponding character in the replacement list.
1026It returns the number of characters replaced.
1027If no string is specified via the =~ or !~ operator,
1028the $_ string is translated.
1029(The string specified with =~ must be a scalar variable, an array element,
1030or an assignment to one of those, i.e. an lvalue.)
1031For
1032.I sed
1033devotees,
1034.I y
1035is provided as a synonym for
1036.IR tr .
1037Examples:
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
ae986130 1051.Ip "umask" 8
a687059c 1052Sets the umask for the process and returns the old one.
1053If EXPR is omitted, merely returns current umask.
1054.Ip "undef(EXPR)" 8 6
1055.Ip "undef EXPR" 8
1056.Ip "undef" 8
1057Undefines the value of EXPR, which must be an lvalue.
1058Use 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
1060dbm array values.)
1061Always returns the undefined value.
1062You can omit the EXPR, in which case nothing is undefined, but you still
1063get an undefined value that you could, for instance, return from a subroutine.
1064Examples:
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
1078Deletes a list of files.
1079Returns 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
1088Note: unlink will not delete directories unless you are superuser and the
1089.B \-U
1090flag is supplied to
1091.IR perl .
1092Even if these conditions are met, be warned that unlinking a directory
1093can inflict damage on your filesystem.
1094Use rmdir instead.
1095.Ip "unpack(TEMPLATE,EXPR)" 8 4
1096Unpack does the reverse of pack: it takes a string representing
1097a structure and expands it out into an array value, returning the array
1098value.
1099The TEMPLATE has the same format as in the pack function.
1100Here'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
1110and then there's
1111
1112 sub ord { unpack("c",$_[0]); }
1113
1114.fi
1115.Ip "unshift(ARRAY,LIST)" 8 4
1116Does the opposite of a
1117.IR shift .
1118Or the opposite of a
1119.IR push ,
1120depending on how you look at it.
1121Prepends list to the front of the array, and returns the number of elements
1122in 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
1130Changes the access and modification times on each file of a list of files.
1131The first two elements of the list must be the NUMERICAL access and
1132modification times, in that order.
1133Returns the number of files successfully changed.
1134The inode modification time of each file is set to the current time.
1135Example 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
1146Returns a normal array consisting of all the values of the named associative
1147array.
1148The values are returned in an apparently random order, but it is the same order
1149as either the keys() or each() function would produce on the same array.
1150See also keys() and each().
1151.Ip "vec(EXPR,OFFSET,BITS)" 8 2
1152Treats a string as a vector of unsigned integers, and returns the value
1153of the bitfield specified.
1154May also be assigned to.
1155BITS must be a power of two from 1 to 32.
1156.Sp
1157Vectors created with vec() can also be manipulated with the logical operators
1158|, & and ^,
1159which will assume a bit vector operation is desired when both operands are
1160strings.
1161This interpretation is not enabled unless there is at least one vec() in
1162your program, to protect older programs.
1163.Ip "wait" 8 6
1164Waits for a child process to terminate and returns the pid of the deceased
ae986130 1165process, or -1 if there are no child processes.
a687059c 1166The status is returned in $?.
ae986130 1167If you expected a child and didn't find it, you probably had a call to
1168system, a close on a pipe, or backticks between the fork and the wait.
1169These constructs also do a wait and may have harvested your child process.
a687059c 1170.Ip "wantarray" 8 4
1171Returns true if the context of the currently executing subroutine
1172is looking for an array value.
1173Returns 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
1181Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
1182.Ip "write(FILEHANDLE)" 8 6
1183.Ip "write(EXPR)" 8
ae986130 1184.Ip "write" 8
a687059c 1185Writes a formatted record (possibly multi-line) to the specified file,
1186using the format associated with that file.
1187By default the format for a file is the one having the same name is the
1188filehandle, but the format for the current output channel (see
1189.IR select )
1190may be set explicitly
1191by assigning the name of the format to the $~ variable.
1192.Sp
1193Top of form processing is handled automatically:
1194if there is insufficient room on the current page for the formatted
ac58e20f 1195record, the page is advanced by writing a form feed,
1196a special top-of-page format is used
a687059c 1197to format the new page header, and then the record is written.
1198By default the top-of-page format is \*(L"top\*(R", but it
1199may be set to the
1200format of your choice by assigning the name to the $^ variable.
ac58e20f 1201The number of lines remaining on the current page is in variable $-, which
1202can be set to 0 to force a new page.
a687059c 1203.Sp
1204If FILEHANDLE is unspecified, output goes to the current default output channel,
1205which starts out as
1206.I STDOUT
1207but may be changed by the
1208.I select
1209operator.
1210If the FILEHANDLE is an EXPR, then the expression is evaluated and the
1211resulting string is used to look up the name of the FILEHANDLE at run time.
1212For more on formats, see the section on formats later on.
1213.Sp
1214Note that write is NOT the opposite of read.