1 ''' Beginning of part 3
2 ''' $Header: perl.man.3,v 3.0.1.3 89/12/21 20:10:12 lwall Locked $
4 ''' $Log: perl.man.3,v $
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
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
13 ''' Revision 3.0.1.1 89/11/11 04:45:06 lwall
14 ''' patch2: made some line breaks depend on troff vs. nroff
16 ''' Revision 3.0 89/10/18 15:21:46 lwall
25 statement in C; it starts the next iteration of the loop:
29 line: while (<STDIN>) {
30 next line if /\|^#/; # discard comments
35 Note that if there were a
37 block on the above, it would get executed even on discarded lines.
38 If the LABEL is omitted, the command refers to the innermost enclosing loop.
41 Returns 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.)
43 The following will handle decimal, octal and hex in the standard notation:
46 $val = oct($val) if $val =~ /^0/;
49 If EXPR is omitted, uses $_.
50 .Ip "open(FILEHANDLE,EXPR)" 8 8
51 .Ip "open(FILEHANDLE)" 8
52 .Ip "open FILEHANDLE" 8
53 Opens the file whose filename is given by EXPR, and associates it with
55 If FILEHANDLE is an expression, its value is used as the name of the
56 real filehandle wanted.
57 If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
58 contains the filename.
59 If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
61 If the filename begins with \*(L">\*(R", the file is opened for output.
62 If 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
64 want both read and write access to the file.)
65 If the filename begins with \*(L"|\*(R", the filename is interpreted
66 as a command to which output is to be piped, and if the filename ends
67 with a \*(L"|\*(R", the filename is interpreted as command which pipes
69 (You may not have a command that pipes both in and out.)
72 and opening \'>\-\' opens
74 Open returns non-zero upon success, the undefined value otherwise.
75 If the open involved a pipe, the return value happens to be the pid
82 open article || die "Can't find article $article: $!\en";
83 while (<article>) {\|.\|.\|.
86 open(LOG, \'>>/usr/spool/news/twitlog\'\|); # (log is reserved)
89 open(LOG, \'>>/usr/spool/news/twitlog\'\|);
94 open(article, "caesar <$article |"\|); # decrypt article
97 open(article, "caesar <$article |"\|);
102 open(extract, "|sort >/tmp/Tmp$$"\|); # $$ is our process#
105 open(extract, "|sort >/tmp/Tmp$$"\|);
110 # process argument list of files along with any includes
112 foreach $file (@ARGV) {
113 do process($file, \'fh00\'); # no pun intended
117 local($filename, $input) = @_;
118 $input++; # this is a string increment
119 unless (open($input, $filename)) {
120 print STDERR "Can't open $filename: $!\en";
124 while (<$input>) { # note the use of indirection
127 while (<$input>) { # note use of indirection
129 if (/^#include "(.*)"/) {
130 do process($1, $input);
138 You may also, in the Bourne shell tradition, specify an EXPR beginning
139 with \*(L">&\*(R", in which case the rest of the string
140 is interpreted as the name of a filehandle
141 (or file descriptor, if numeric) which is to be duped and opened.
142 You may use & after >, >>, <, +>, +>> and +<.
143 The mode you specify should match the mode of the original filehandle.
144 Here is a script that saves, redirects, and restores
152 open(SAVEOUT, ">&STDOUT");
153 open(SAVEERR, ">&STDERR");
155 open(STDOUT, ">foo.out") || die "Can't redirect stdout";
156 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
158 select(STDERR); $| = 1; # make unbuffered
159 select(STDOUT); $| = 1; # make unbuffered
161 print STDOUT "stdout 1\en"; # this works for
162 print STDERR "stderr 1\en"; # subprocesses too
167 open(STDOUT, ">&SAVEOUT");
168 open(STDERR, ">&SAVEERR");
170 print STDOUT "stdout 2\en";
171 print STDERR "stderr 2\en";
174 If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
175 then there is an implicit fork done, and the return value of open
176 is the pid of the child within the parent process, and 0 within the child
178 (Use defined($pid) to determine if the open was successful.)
179 The filehandle behaves normally for the parent, but i/o to that
180 filehandle is piped from/to the
182 of the child process.
183 In the child process the filehandle isn't opened\*(--i/o happens from/to
188 Typically this is used like the normal piped open when you want to exercise
189 more control over just how the pipe command gets executed, such as when
190 you are running setuid, and don't want to have to scan shell commands
192 The following pairs are equivalent:
196 open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
197 open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
199 open(FOO, "cat \-n $file|");
200 open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
203 Explicitly closing any piped filehandle causes the parent process to wait for the
204 child to finish, and returns the status value in $?.
205 .Ip "opendir(DIRHANDLE,EXPR)" 8 3
206 Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
207 rewinddir() and closedir().
208 Returns true if successful.
209 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
212 Returns the ascii value of the first character of EXPR.
213 If EXPR is omitted, uses $_.
214 .Ip "pack(TEMPLATE,LIST)" 8 4
215 Takes an array or list of values and packs it into a binary structure,
216 returning the string containing the structure.
217 The TEMPLATE is a sequence of characters that give the order and type
218 of values, as follows:
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.
237 Each letter may optionally be followed by a number which gives a repeat
239 With all types except "a" and "A" the pack function will gobble up that many values
241 The "a" and "A" types gobble just one value, but pack it as a string that long,
242 padding with nulls or spaces as necessary.
243 (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
247 $foo = pack("cccc",65,66,67,68);
249 $foo = pack("c4",65,66,67,68);
252 $foo = pack("ccxxcc",65,66,67,68);
253 # foo eq "AB\e0\e0CD"
255 $foo = pack("s2",1,2);
256 # "\e1\e0\e2\e0" on little-endian
257 # "\e0\e1\e0\e2" on big-endian
259 $foo = pack("a4","abcd","x","y","z");
262 $foo = pack("aaaa","abcd","x","y","z");
265 $foo = pack("a14","abcdefg");
266 # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
268 $foo = pack("i9pl", gmtime);
269 # a real struct tm (on my system anyway)
272 The same template may generally also be used in the unpack function.
275 Pops and returns the last value of the array, shortening the array by 1.
276 Has the same effect as
279 $tmp = $ARRAY[$#ARRAY\-\|\-];
282 If there are no elements in the array, returns the undefined value.
283 .Ip "print(FILEHANDLE LIST)" 8 10
285 .Ip "print FILEHANDLE LIST" 8
288 Prints a string or a comma-separated list of strings.
289 Returns non-zero if successful.
290 FILEHANDLE may be a scalar variable name, in which case the variable contains
291 the name of the filehandle, thus introducing one level of indirection.
292 If FILEHANDLE is omitted, prints by default to standard output (or to the
293 last selected output channel\*(--see select()).
294 If LIST is also omitted, prints $_ to
296 To set the default output channel to something other than
298 use the select operation.
299 Note that, because print takes a LIST, anything in the LIST is evaluated
300 in an array context, and any subroutine that you call will have one or more
301 of its expressions evaluated in an array context.
302 .Ip "printf(FILEHANDLE LIST)" 8 10
304 .Ip "printf FILEHANDLE LIST" 8
306 Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
307 .Ip "push(ARRAY,LIST)" 8 7
308 Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
309 onto the end of ARRAY.
310 The length of ARRAY increases by the length of LIST.
311 Has the same effect as
315 $ARRAY[++$#ARRAY] = $value;
319 but is more efficient.
322 These are not really functions, but simply syntactic sugar to let you
323 avoid putting too many backslashes into quoted strings.
324 The q operator is a generalized single quote, and the qq operator a
325 generalized double quote.
326 Any delimiter can be used in place of /, including newline.
327 If the delimiter is an opening bracket or parenthesis, the final delimiter
328 will be the corresponding closing bracket or parenthesis.
329 (Embedded occurrences of the closing bracket need to be backslashed as usual.)
334 $foo = q!I said, "You said, \'She said it.\'"!;
335 $bar = q(\'This is it.\');
337 *** The previous line contains the naughty word "$&".\en
338 if /(ibm|apple|awk)/; # :-)
344 Returns a random fractional number between 0 and the value of EXPR.
345 (EXPR should be positive.)
346 If EXPR is omitted, returns a value between 0 and 1.
348 .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
349 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
351 Returns the number of bytes actually read.
352 SCALAR will be grown or shrunk to the length actually read.
353 .Ip "readdir(DIRHANDLE)" 8 3
354 .Ip "readdir DIRHANDLE" 8
355 Returns the next directory entry for a directory opened by opendir().
356 If used in an array context, returns all the rest of the entries in the
358 If there are no more entries, returns an undefined value in a scalar context
359 or a null list in an array context.
360 .Ip "readlink(EXPR)" 8 6
361 .Ip "readlink EXPR" 8
362 Returns the value of a symbolic link, if symbolic links are implemented.
363 If not, gives a fatal error.
364 If there is some system error, returns the undefined value and sets $! (errno).
365 If EXPR is omitted, uses $_.
366 .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
367 Receives a message on a socket.
368 Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
370 Returns the address of the sender, or the undefined value if there's an error.
371 SCALAR will be grown or shrunk to the length actually read.
372 Takes the same flags as the system call of the same name.
377 command restarts the loop block without evaluating the conditional again.
380 block, if any, is not executed.
381 If the LABEL is omitted, the command refers to the innermost enclosing loop.
382 This command is normally used by programs that want to lie to themselves
383 about what was just input:
387 # a simpleminded Pascal comment stripper
388 # (warning: assumes no { or } in strings)
389 line: while (<STDIN>) {
390 while (s|\|({.*}.*\|){.*}|$1 \||) {}
395 if (\|/\|}/\|) { # end of comment?
405 .Ip "rename(OLDNAME,NEWNAME)" 8 2
406 Changes the name of a file.
407 Returns 1 for success, 0 otherwise.
408 Will not work across filesystem boundaries.
409 .Ip "reset(EXPR)" 8 6
414 block at the end of a loop to clear variables and reset ?? searches
415 so that they work again.
416 The expression is interpreted as a list of single characters (hyphens allowed
418 All variables and arrays beginning with one of those letters are reset to
419 their pristine state.
420 If the expression is omitted, one-match searches (?pattern?) are reset to
422 Only resets variables or searches in the current package.
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
433 Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
436 The 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
438 you are sharing the dbm file.
439 Then again, maybe not.)
440 .Ip "return LIST" 8 3
441 Returns from a subroutine with the value specified.
442 (Note that a subroutine can automatically return
443 the value of the last expression evaluated.
444 That's the preferred method\*(--use of an explicit
447 .Ip "reverse(LIST)" 8 4
449 Returns an array value consisting of the elements of LIST in the opposite order.
450 .Ip "rewinddir(DIRHANDLE)" 8 5
451 .Ip "rewinddir DIRHANDLE" 8
452 Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
453 .Ip "rindex(STR,SUBSTR)" 8 4
454 Works just like index except that it
455 returns the position of the LAST occurrence of SUBSTR in STR.
456 .Ip "rmdir(FILENAME)" 8 4
457 .Ip "rmdir FILENAME" 8
458 Deletes the directory specified by FILENAME if it is empty.
459 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
460 If FILENAME is omitted, uses $_.
461 .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
462 Searches a string for a pattern, and if found, replaces that pattern with the
463 replacement text and returns the number of substitutions made.
464 Otherwise it returns false (0).
465 The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
466 of the pattern are to be replaced.
467 The \*(L"i\*(R" is also optional, and if present, indicates that matching
468 is to be done in a case-insensitive manner.
469 The \*(L"e\*(R" is likewise optional, and if present, indicates that
470 the replacement string is to be evaluated as an expression rather than just
471 as a double-quoted string.
472 Any delimiter may replace the slashes; if single quotes are used, no
473 interpretation is done on the replacement string (the e modifier overrides
474 this, however); if backquotes are used, the replacement string is a command
475 to execute whose output will be used as the actual replacement text.
476 If no string is specified via the =~ or !~ operator,
477 the $_ string is searched and modified.
478 (The string specified with =~ must be a scalar variable, an array element,
479 or an assignment to one of those, i.e. an lvalue.)
480 If the pattern contains a $ that looks like a variable rather than an
481 end-of-string test, the variable will be interpolated into the pattern at
483 If you only want the pattern compiled once the first time the variable is
484 interpolated, add an \*(L"o\*(R" at the end.
485 See also the section on regular expressions.
489 s/\|\e\|bgreen\e\|b/mauve/g; # don't change wintergreen
491 $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
493 s/Login: $foo/Login: $bar/; # run-time pattern
495 ($foo = $bar) =~ s/bar/foo/;
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'
502 s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/; # reverse 1st two fields
505 (Note the use of $ instead of \|\e\| in the last example. See section
506 on regular expressions.)
507 .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
508 Randomly positions the file pointer for FILEHANDLE, just like the fseek()
510 FILEHANDLE may be an expression whose value gives the name of the filehandle.
511 Returns 1 upon success, 0 otherwise.
512 .Ip "seekdir(DIRHANDLE,POS)" 8 3
513 Sets the current position for the readdir() routine on DIRHANDLE.
514 POS must be a value returned by seekdir().
515 Has the same caveats about possible directory compaction as the corresponding
516 system library routine.
517 .Ip "select(FILEHANDLE)" 8 3
519 Returns the currently selected filehandle.
520 Sets the current default filehandle for output, if FILEHANDLE is supplied.
521 This has two effects: first, a
525 without a filehandle will default to this FILEHANDLE.
526 Second, references to variables related to output will refer to this output
528 For example, if you have to set the top of form format for more than
529 one output channel, you might do the following:
534 $^ = \'report1_top\';
536 $^ = \'report2_top\';
539 FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
543 $oldfh = select(STDERR); $| = 1; select($oldfh);
546 .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
547 This calls the select system call with the bitmasks specified, which can
548 be constructed using fileno() and vec(), along these lines:
551 $rin = $win = $ein = '';
552 vec($rin,fileno(STDIN),1) = 1;
553 vec($win,fileno(STDOUT),1) = 1;
557 If you want to select on many filehandles you might wish to write a subroutine:
561 local(@fhlist) = split(' ',$_[0]);
564 vec($bits,fileno($_),1) = 1;
568 $rin = &fhbits('STDIN TTY SOCK');
574 ($nfound,$timeleft) =
575 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
577 or to block until something becomes ready:
580 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
583 $nfound = select($rout=$rin, $wout=$win,
588 Any of the bitmasks can also be undef.
589 The timeout, if specified, is in seconds, which may be fractional.
590 NOTE: not all implementations are capable of returning the $timeleft.
591 If not, they always return $timeleft equal to the supplied $timeout.
592 .Ip "setpgrp(PID,PGRP)" 8 4
593 Sets the current process group for the specified PID, 0 for the current
595 Will produce a fatal error if used on a machine that doesn't implement
597 .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
598 .Ip "send(SOCKET,MSG,FLAGS)" 8
599 Sends a message on a socket.
600 Takes the same flags as the system call of the same name.
601 On unconnected sockets you must specify a destination to send TO.
602 Returns the number of characters sent, or the undefined value if
604 .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
605 Sets the current priority for a process, a process group, or a user.
606 (See setpriority(2).)
607 Will produce a fatal error if used on a machine that doesn't implement
609 .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
610 Sets the socket option requested.
611 Returns undefined if there is an error.
612 OPTVAL may be specified as undef if you don't want to pass an argument.
613 .Ip "shift(ARRAY)" 8 6
616 Shifts the first value of the array off and returns it,
617 shortening the array by 1 and moving everything down.
618 If there are no elements in the array, returns the undefined value.
619 If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
620 array in subroutines.
621 See also unshift(), push() and pop().
622 Shift() and unshift() do the same thing to the left end of an array that push()
623 and pop() do to the right end.
624 .Ip "shutdown(SOCKET,HOW)" 8 3
625 Shuts down a socket connection in the manner indicated by HOW, which has
626 the same interpretation as in the system call of the same name.
629 Returns the sine of EXPR (expressed in radians).
630 If EXPR is omitted, returns sine of $_.
631 .Ip "sleep(EXPR)" 8 6
634 Causes the script to sleep for EXPR seconds, or forever if no EXPR.
635 May be interrupted by sending the process a SIGALARM.
636 Returns the number of seconds actually slept.
637 .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
638 Opens a socket of the specified kind and attaches it to filehandle SOCKET.
639 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
641 You may need to run makelib on sys/socket.h to get the proper values handy
642 in a perl library file.
643 Return true if successful.
644 See the example in the section on Interprocess Communication.
645 .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
646 Creates an unnamed pair of sockets in the specified domain, of the specified
648 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
650 If unimplemented, yields a fatal error.
651 Return true if successful.
652 .Ip "sort(SUBROUTINE LIST)" 8 9
654 .Ip "sort SUBROUTINE LIST" 8
656 Sorts the LIST and returns the sorted array value.
657 Nonexistent values of arrays are stripped out.
658 If SUBROUTINE is omitted, sorts in standard string comparison order.
659 If SUBROUTINE is specified, gives the name of a subroutine that returns
660 an integer less than, equal to, or greater than 0,
661 depending on how the elements of the array are to be ordered.
662 In the interests of efficiency the normal calling code for subroutines
663 is bypassed, with the following effects: the subroutine may not be a recursive
664 subroutine, and the two elements to be compared are passed into the subroutine
665 not via @_ but as $a and $b (see example below).
666 They are passed by reference so don't modify $a and $b.
667 SUBROUTINE may be a scalar variable name, in which case the value provides
668 the name of the subroutine to use.
674 $age{$a} - $age{$b}; # presuming integers
676 @sortedclass = sort byage @class;
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\');
683 # prints AbelCaincatdogx
684 print sort reverse @harry;
685 # prints xdogcatCainAbel
686 print sort @george, \'to\', @harry;
687 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
690 .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
691 .Ip "split(/PATTERN/,EXPR)" 8 8
692 .Ip "split(/PATTERN/)" 8
694 Splits 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
697 If EXPR is omitted, splits the $_ string.
698 If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
699 Anything matching PATTERN is taken to be a delimiter separating the fields.
700 (Note that the delimiter may be longer than one character.)
701 If LIMIT is specified, splits into no more than that many fields (though it
702 may split into fewer).
703 If LIMIT is unspecified, trailing null fields are stripped (which
704 potential users of pop() would do well to remember).
705 A pattern matching the null string (not to be confused with a null pattern,
706 which is one member of the set of patterns matching a null string)
707 will split the value of EXPR into separate characters at each point it
712 print join(\':\', split(/ */, \'hi there\'));
715 produces the output \*(L'h:i:t:h:e:r:e\*(R'.
717 The LIMIT parameter can be used to partially split a line
720 ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
723 (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
724 larger than the number of variables in the list, to avoid unnecessary work.
725 For the list above LIMIT would have been 4 by default.
726 In time critical applications it behooves you not to split into
727 more fields than you really need.)
729 If the PATTERN contains parentheses, additional array elements are created
730 from each matching substring in the delimiter.
732 split(/([,-])/,"1-10,20");
734 produces the array value
738 The pattern /PATTERN/ may be replaced with an expression to specify patterns
739 that vary at runtime.
740 (To do runtime compilation only once, use /$variable/o.)
741 As a special case, specifying a space (\'\ \') will split on white space
742 just as split with no arguments does, but leading white space does NOT
743 produce a null first field.
744 Thus, split(\'\ \') can be used to emulate
746 default behavior, whereas
747 split(/\ /) will give you as many null initial fields as there are
754 open(passwd, \'/etc/passwd\');
757 ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
760 ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
761 = split(\|/\|:\|/\|);
767 (Note that $shell above will still have a newline on it. See chop().)
770 .Ip "sprintf(FORMAT,LIST)" 8 4
771 Returns a string formatted by the usual printf conventions.
772 The * character is not supported.
775 Return the square root of EXPR.
776 If EXPR is omitted, returns square root of $_.
777 .Ip "srand(EXPR)" 8 4
779 Sets the random number seed for the
782 If EXPR is omitted, does srand(time).
783 .Ip "stat(FILEHANDLE)" 8 8
784 .Ip "stat FILEHANDLE" 8
786 .Ip "stat SCALARVARIABLE" 8
787 Returns a 13-element array giving the statistics for a file, either the file
788 opened via FILEHANDLE, or named by EXPR.
789 Typically used as follows:
793 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
794 $atime,$mtime,$ctime,$blksize,$blocks)
798 If stat is passed the special filehandle consisting of an underline,
799 no stat is done, but the current contents of the stat structure from
800 the last stat or filetest are returned.
805 if (-x $file && (($d) = stat(_)) && $d < 0) {
806 print "$file is executable NFS file\en";
810 .Ip "study(SCALAR)" 8 6
813 Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
814 doing many pattern matches on the string before it is next modified.
815 This may or may not save time, depending on the nature and number of patterns
816 you are searching on, and on the distribution of character frequencies in
817 the string to be searched\*(--you probably want to compare runtimes with and
818 without it to see which runs faster.
819 Those loops which scan for many short constant strings (including the constant
820 parts of more complex patterns) will benefit most.
821 You may have only one study active at a time\*(--if you study a different
822 scalar the first is \*(L"unstudied\*(R".
823 (The way study works is this: a linked list of every character in the string
824 to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
826 From each search string, the rarest character is selected, based on some
827 static frequency tables constructed from some C programs and English text.
828 Only those places that contain this \*(L"rarest\*(R" character are examined.)
830 For example, here is a loop which inserts index producing entries before any line
831 containing a certain pattern:
837 print ".IX foo\en" if /\ebfoo\eb/;
838 print ".IX bar\en" if /\ebbar\eb/;
839 print ".IX blurfl\en" if /\ebblurfl\eb/;
845 In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
846 will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
847 In general, this is a big win except in pathological cases.
848 The only question is whether it saves you more time than it took to build
849 the linked list in the first place.
851 Note that if you have to look for strings that you don't know till runtime,
852 you can build an entire loop as a string and eval that to avoid recompiling
853 all your patterns all the time.
854 Together with setting $/ to input entire files as one record, this can
855 be very fast, often faster than specialized programs like fgrep.
856 The following scans a list of files (@files)
857 for a list of words (@words), and prints out the names of those files that
862 $search = \'while (<>) { study;\';
863 foreach $word (@words) {
864 $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
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)) {
876 .Ip "substr(EXPR,OFFSET,LEN)" 8 2
877 Extracts a substring out of EXPR and returns it.
878 First character is at offset 0, or whatever you've set $[ to.
879 If OFFSET is negative, starts that far from the end of the string.
880 You can use the substr() function as an lvalue, in which case EXPR must
882 If you assign something shorter than LEN, the string will shrink, and
883 if you assign something longer than LEN, the string will grow to accommodate it.
884 To keep the string the same length you may need to pad or chop your value using
886 .Ip "syscall(LIST)" 8 6
888 Calls the system call specified as the first element of the list, passing
889 the remaining elements as arguments to the system call.
890 If unimplemented, produces a fatal error.
891 The arguments are interpreted as follows: if a given argument is numeric,
892 the argument is passed as an int.
893 If not, the pointer to the string value is passed.
894 You are responsible to make sure a string is pre-extended long enough
895 to receive any result that might be written into a string.
896 If your integer arguments are not literals and have never been interpreted
897 in a numeric context, you may need to add 0 to them to force them to look
901 do 'syscall.h'; # may need to run makelib
902 syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
905 .Ip "system(LIST)" 8 6
907 Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
908 is done first, and the parent process waits for the child process to complete.
909 Note that argument processing varies depending on the number of arguments.
910 The return value is the exit status of the program as returned by the wait()
912 To get the actual exit value divide by 256.
915 .Ip "symlink(OLDFILE,NEWFILE)" 8 2
916 Creates a new filename symbolically linked to the old filename.
917 Returns 1 for success, 0 otherwise.
918 On systems that don't support symbolic links, produces a fatal error at
920 To check for that, use eval:
923 $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
926 .Ip "tell(FILEHANDLE)" 8 6
927 .Ip "tell FILEHANDLE" 8 6
929 Returns the current file position for FILEHANDLE.
930 FILEHANDLE may be an expression whose value gives the name of the actual
932 If FILEHANDLE is omitted, assumes the file last read.
933 .Ip "telldir(DIRHANDLE)" 8 5
934 .Ip "telldir DIRHANDLE" 8
935 Returns the current position of the readdir() routines on DIRHANDLE.
936 Value may be given to seekdir() to access a particular location in
938 Has the same caveats about possible directory compaction as the corresponding
939 system library routine.
941 Returns the number of non-leap seconds since January 1, 1970, UTC.
942 Suitable for feeding to gmtime() and localtime().
944 Returns a four-element array giving the user and system times, in seconds, for this
945 process and the children of this process.
947 ($user,$system,$cuser,$csystem) = times;
949 .Ip "tr/SEARCHLIST/REPLACEMENTLIST/" 8 5
950 .Ip "y/SEARCHLIST/REPLACEMENTLIST/" 8
951 Translates all occurrences of the characters found in the search list with
952 the corresponding character in the replacement list.
953 It returns the number of characters replaced.
954 If no string is specified via the =~ or !~ operator,
955 the $_ string is translated.
956 (The string specified with =~ must be a scalar variable, an array element,
957 or an assignment to one of those, i.e. an lvalue.)
962 is provided as a synonym for
967 $ARGV[1] \|=~ \|y/A\-Z/a\-z/; \h'|3i'# canonicalize to lower case
969 $cnt = tr/*/*/; \h'|3i'# count the stars in $_
971 ($HOST = $host) =~ tr/a\-z/A\-Z/;
973 y/\e001\-@[\-_{\-\e177/ /; \h'|3i'# change non-alphas to space
976 .Ip "umask(EXPR)" 8 4
979 Sets the umask for the process and returns the old one.
980 If EXPR is omitted, merely returns current umask.
981 .Ip "undef(EXPR)" 8 6
984 Undefines the value of EXPR, which must be an lvalue.
985 Use 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
988 Always returns the undefined value.
989 You can omit the EXPR, in which case nothing is undefined, but you still
990 get an undefined value that you could, for instance, return from a subroutine.
996 undef $bar{'blurfl'};
1000 return (wantarray ? () : undef) if $they_blew_it;
1003 .Ip "unlink(LIST)" 8 4
1005 Deletes a list of files.
1006 Returns the number of files successfully deleted.
1010 $cnt = unlink \'a\', \'b\', \'c\';
1015 Note: unlink will not delete directories unless you are superuser and the
1019 Even if these conditions are met, be warned that unlinking a directory
1020 can inflict damage on your filesystem.
1022 .Ip "unpack(TEMPLATE,EXPR)" 8 4
1023 Unpack does the reverse of pack: it takes a string representing
1024 a structure and expands it out into an array value, returning the array
1026 The TEMPLATE has the same format as in the pack function.
1027 Here's a subroutine that does substring:
1032 local($what,$where,$howmuch) = @_;
1033 unpack("x$where a$howmuch", $what);
1039 sub ord { unpack("c",$_[0]); }
1042 .Ip "unshift(ARRAY,LIST)" 8 4
1043 Does the opposite of a
1045 Or the opposite of a
1047 depending on how you look at it.
1048 Prepends list to the front of the array, and returns the number of elements
1052 unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
1055 .Ip "utime(LIST)" 8 2
1056 .Ip "utime LIST" 8 2
1057 Changes the access and modification times on each file of a list of files.
1058 The first two elements of the list must be the NUMERICAL access and
1059 modification times, in that order.
1060 Returns the number of files successfully changed.
1061 The inode modification time of each file is set to the current time.
1062 Example of a \*(L"touch\*(R" command:
1068 utime $now, $now, @ARGV;
1071 .Ip "values(ASSOC_ARRAY)" 8 6
1072 .Ip "values ASSOC_ARRAY" 8
1073 Returns a normal array consisting of all the values of the named associative
1075 The values are returned in an apparently random order, but it is the same order
1076 as either the keys() or each() function would produce on the same array.
1077 See also keys() and each().
1078 .Ip "vec(EXPR,OFFSET,BITS)" 8 2
1079 Treats a string as a vector of unsigned integers, and returns the value
1080 of the bitfield specified.
1081 May also be assigned to.
1082 BITS must be a power of two from 1 to 32.
1084 Vectors created with vec() can also be manipulated with the logical operators
1086 which will assume a bit vector operation is desired when both operands are
1088 This interpretation is not enabled unless there is at least one vec() in
1089 your program, to protect older programs.
1091 Waits for a child process to terminate and returns the pid of the deceased
1092 process, or -1 if there are no child processes.
1093 The status is returned in $?.
1094 If you expected a child and didn't find it, you probably had a call to
1095 system, a close on a pipe, or backticks between the fork and the wait.
1096 These constructs also do a wait and may have harvested your child process.
1098 Returns true if the context of the currently executing subroutine
1099 is looking for an array value.
1100 Returns false if the context is looking for a scalar.
1103 return wantarray ? () : undef;
1106 .Ip "warn(LIST)" 8 4
1108 Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
1109 .Ip "write(FILEHANDLE)" 8 6
1112 Writes a formatted record (possibly multi-line) to the specified file,
1113 using the format associated with that file.
1114 By default the format for a file is the one having the same name is the
1115 filehandle, but the format for the current output channel (see
1117 may be set explicitly
1118 by assigning the name of the format to the $~ variable.
1120 Top of form processing is handled automatically:
1121 if there is insufficient room on the current page for the formatted
1122 record, the page is advanced, a special top-of-page format is used
1123 to format the new page header, and then the record is written.
1124 By default the top-of-page format is \*(L"top\*(R", but it
1126 format of your choice by assigning the name to the $^ variable.
1128 If FILEHANDLE is unspecified, output goes to the current default output channel,
1131 but may be changed by the
1134 If the FILEHANDLE is an EXPR, then the expression is evaluated and the
1135 resulting string is used to look up the name of the FILEHANDLE at run time.
1136 For more on formats, see the section on formats later on.
1138 Note that write is NOT the opposite of read.