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