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