1 ''' Beginning of part 3
2 ''' $Header: perl_man.3,v 3.0.1.12 91/01/11 18:18:15 lwall Locked $
4 ''' $Log: perl.man.3,v $
5 ''' Revision 3.0.1.12 91/01/11 18:18:15 lwall
6 ''' patch42: added binary and hex pack/unpack options
8 ''' Revision 3.0.1.11 90/11/10 01:48:21 lwall
9 ''' patch38: random cleanup
10 ''' patch38: documented tr///cds
12 ''' Revision 3.0.1.10 90/10/20 02:15:17 lwall
13 ''' patch37: patch37: fixed various typos in man page
15 ''' Revision 3.0.1.9 90/10/16 10:02:43 lwall
16 ''' patch29: you can now read into the middle string
17 ''' patch29: index and substr now have optional 3rd args
18 ''' patch29: added scalar reverse
19 ''' patch29: added scalar
20 ''' patch29: added SysV IPC
21 ''' patch29: added waitpid
22 ''' patch29: added sysread and syswrite
24 ''' Revision 3.0.1.8 90/08/09 04:39:04 lwall
25 ''' patch19: added require operator
26 ''' patch19: added truncate operator
27 ''' patch19: unpack can do checksumming
29 ''' Revision 3.0.1.7 90/08/03 11:15:42 lwall
30 ''' patch19: Intermediate diffs for Randal
32 ''' Revision 3.0.1.6 90/03/27 16:17:56 lwall
33 ''' patch16: MSDOS support
35 ''' Revision 3.0.1.5 90/03/12 16:52:21 lwall
36 ''' patch13: documented that print $filehandle &foo is ambiguous
37 ''' patch13: added splice operator: @oldelems = splice(@array,$offset,$len,LIST)
39 ''' Revision 3.0.1.4 90/02/28 18:00:09 lwall
40 ''' patch9: added pipe function
41 ''' patch9: documented how to handle arbitrary weird characters in filenames
42 ''' patch9: documented the unflushed buffers problem on piped opens
43 ''' patch9: documented how to force top of page
45 ''' Revision 3.0.1.3 89/12/21 20:10:12 lwall
46 ''' patch7: documented that s`pat`repl` does command substitution on replacement
47 ''' patch7: documented that $timeleft from select() is likely not implemented
49 ''' Revision 3.0.1.2 89/11/17 15:31:05 lwall
50 ''' patch5: fixed some manual typos and indent problems
51 ''' patch5: added warning about print making an array context
53 ''' Revision 3.0.1.1 89/11/11 04:45:06 lwall
54 ''' patch2: made some line breaks depend on troff vs. nroff
56 ''' Revision 3.0 89/10/18 15:21:46 lwall
65 statement in C; it starts the next iteration of the loop:
69 line: while (<STDIN>) {
70 next line if /\|^#/; # discard comments
75 Note that if there were a
77 block on the above, it would get executed even on discarded lines.
78 If the LABEL is omitted, the command refers to the innermost enclosing loop.
81 Returns the decimal value of EXPR interpreted as an octal string.
82 (If EXPR happens to start off with 0x, interprets it as a hex string instead.)
83 The following will handle decimal, octal and hex in the standard notation:
86 $val = oct($val) if $val =~ /^0/;
89 If EXPR is omitted, uses $_.
90 .Ip "open(FILEHANDLE,EXPR)" 8 8
91 .Ip "open(FILEHANDLE)" 8
92 .Ip "open FILEHANDLE" 8
93 Opens the file whose filename is given by EXPR, and associates it with
95 If FILEHANDLE is an expression, its value is used as the name of the
96 real filehandle wanted.
97 If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
98 contains the filename.
99 If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
101 If the filename begins with \*(L">\*(R", the file is opened for output.
102 If the filename begins with \*(L">>\*(R", the file is opened for appending.
103 (You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
104 want both read and write access to the file.)
105 If the filename begins with \*(L"|\*(R", the filename is interpreted
106 as a command to which output is to be piped, and if the filename ends
107 with a \*(L"|\*(R", the filename is interpreted as command which pipes
109 (You may not have a command that pipes both in and out.)
112 and opening \'>\-\' opens
114 Open returns non-zero upon success, the undefined value otherwise.
115 If the open involved a pipe, the return value happens to be the pid
122 open article || die "Can't find article $article: $!\en";
123 while (<article>) {\|.\|.\|.
126 open(LOG, \'>>/usr/spool/news/twitlog\'\|); # (log is reserved)
129 open(LOG, \'>>/usr/spool/news/twitlog\'\|);
134 open(article, "caesar <$article |"\|); # decrypt article
137 open(article, "caesar <$article |"\|);
142 open(extract, "|sort >/tmp/Tmp$$"\|); # $$ is our process#
145 open(extract, "|sort >/tmp/Tmp$$"\|);
150 # process argument list of files along with any includes
152 foreach $file (@ARGV) {
153 do process($file, \'fh00\'); # no pun intended
157 local($filename, $input) = @_;
158 $input++; # this is a string increment
159 unless (open($input, $filename)) {
160 print STDERR "Can't open $filename: $!\en";
164 while (<$input>) { # note the use of indirection
167 while (<$input>) { # note use of indirection
169 if (/^#include "(.*)"/) {
170 do process($1, $input);
178 You may also, in the Bourne shell tradition, specify an EXPR beginning
179 with \*(L">&\*(R", in which case the rest of the string
180 is interpreted as the name of a filehandle
181 (or file descriptor, if numeric) which is to be duped and opened.
182 You may use & after >, >>, <, +>, +>> and +<.
183 The mode you specify should match the mode of the original filehandle.
184 Here is a script that saves, redirects, and restores
192 open(SAVEOUT, ">&STDOUT");
193 open(SAVEERR, ">&STDERR");
195 open(STDOUT, ">foo.out") || die "Can't redirect stdout";
196 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
198 select(STDERR); $| = 1; # make unbuffered
199 select(STDOUT); $| = 1; # make unbuffered
201 print STDOUT "stdout 1\en"; # this works for
202 print STDERR "stderr 1\en"; # subprocesses too
207 open(STDOUT, ">&SAVEOUT");
208 open(STDERR, ">&SAVEERR");
210 print STDOUT "stdout 2\en";
211 print STDERR "stderr 2\en";
214 If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
215 then there is an implicit fork done, and the return value of open
216 is the pid of the child within the parent process, and 0 within the child
218 (Use defined($pid) to determine if the open was successful.)
219 The filehandle behaves normally for the parent, but i/o to that
220 filehandle is piped from/to the
222 of the child process.
223 In the child process the filehandle isn't opened\*(--i/o happens from/to
228 Typically this is used like the normal piped open when you want to exercise
229 more control over just how the pipe command gets executed, such as when
230 you are running setuid, and don't want to have to scan shell commands
232 The following pairs are more or less equivalent:
236 open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
237 open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
239 open(FOO, "cat \-n '$file'|");
240 open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
243 Explicitly closing any piped filehandle causes the parent process to wait for the
244 child to finish, and returns the status value in $?.
245 Note: on any operation which may do a fork,
246 unflushed buffers remain unflushed in both
247 processes, which means you may need to set $| to
248 avoid duplicate output.
250 The filename that is passed to open will have leading and trailing
252 In order to open a file with arbitrary weird characters in it, it's necessary
253 to protect any leading and trailing whitespace thusly:
257 $file =~ s#^(\es)#./$1#;
258 open(FOO, "< $file\e0");
261 .Ip "opendir(DIRHANDLE,EXPR)" 8 3
262 Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
263 rewinddir() and closedir().
264 Returns true if successful.
265 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
268 Returns the numeric ascii value of the first character of EXPR.
269 If EXPR is omitted, uses $_.
270 ''' Comments on f & d by gnb@melba.bby.oz.au 22/11/89
271 .Ip "pack(TEMPLATE,LIST)" 8 4
272 Takes an array or list of values and packs it into a binary structure,
273 returning the string containing the structure.
274 The TEMPLATE is a sequence of characters that give the order and type
275 of values, as follows:
278 A An ascii string, will be space padded.
279 a An ascii string, will be null padded.
280 c A signed char value.
281 C An unsigned char value.
282 s A signed short value.
283 S An unsigned short value.
284 i A signed integer value.
285 I An unsigned integer value.
286 l A signed long value.
287 L An unsigned long value.
288 n A short in \*(L"network\*(R" order.
289 N A long in \*(L"network\*(R" order.
290 f A single-precision float in the native format.
291 d A double-precision float in the native format.
292 p A pointer to a string.
295 @ Null fill to absolute position.
296 u A uuencoded string.
297 b A bit string (ascending bit order, like vec()).
298 B A bit string (descending bit order).
299 h A hex string (low nybble first).
300 H A hex string (high nybble first).
303 Each letter may optionally be followed by a number which gives a repeat
305 With all types except "a", "A", "b", "B", "h" and "H",
306 the pack function will gobble up that many values
308 A * for the repeat count means to use however many items are left.
309 The "a" and "A" types gobble just one value, but pack it as a string of length
311 padding with nulls or spaces as necessary.
312 (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
313 Likewise, the "b" and "B" fields pack a string that many bits long.
314 The "h" and "H" fields pack a string that many nybbles long.
315 Real numbers (floats and doubles) are in the native machine format
316 only; due to the multiplicity of floating formats around, and the lack
317 of a standard \*(L"network\*(R" representation, no facility for
318 interchange has been made.
319 This means that packed floating point data
320 written on one machine may not be readable on another - even if both
321 use IEEE floating point arithmetic (as the endian-ness of the memory
322 representation is not part of the IEEE spec).
324 doubles internally for all numeric calculation, and converting from
325 double -> float -> double will lose precision (i.e. unpack("f",
326 pack("f", $foo)) will not in general equal $foo).
331 $foo = pack("cccc",65,66,67,68);
333 $foo = pack("c4",65,66,67,68);
336 $foo = pack("ccxxcc",65,66,67,68);
337 # foo eq "AB\e0\e0CD"
339 $foo = pack("s2",1,2);
340 # "\e1\e0\e2\e0" on little-endian
341 # "\e0\e1\e0\e2" on big-endian
343 $foo = pack("a4","abcd","x","y","z");
346 $foo = pack("aaaa","abcd","x","y","z");
349 $foo = pack("a14","abcdefg");
350 # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
352 $foo = pack("i9pl", gmtime);
353 # a real struct tm (on my system anyway)
356 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
359 The same template may generally also be used in the unpack function.
360 .Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
361 Opens a pair of connected pipes like the corresponding system call.
362 Note that if you set up a loop of piped processes, deadlock can occur
363 unless you are very careful.
364 In addition, note that perl's pipes use stdio buffering, so you may need
365 to set $| to flush your WRITEHANDLE after each command, depending on
367 [Requires version 3.0 patchlevel 9.]
370 Pops and returns the last value of the array, shortening the array by 1.
371 Has the same effect as
374 $tmp = $ARRAY[$#ARRAY\-\|\-];
377 If there are no elements in the array, returns the undefined value.
378 .Ip "print(FILEHANDLE LIST)" 8 10
380 .Ip "print FILEHANDLE LIST" 8
383 Prints a string or a comma-separated list of strings.
384 Returns non-zero if successful.
385 FILEHANDLE may be a scalar variable name, in which case the variable contains
386 the name of the filehandle, thus introducing one level of indirection.
387 (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
388 misinterpreted as an operator unless you interpose a + or put parens around
390 If FILEHANDLE is omitted, prints by default to standard output (or to the
391 last selected output channel\*(--see select()).
392 If LIST is also omitted, prints $_ to
394 To set the default output channel to something other than
396 use the select operation.
397 Note that, because print takes a LIST, anything in the LIST is evaluated
398 in an array context, and any subroutine that you call will have one or more
399 of its expressions evaluated in an array context.
400 Also be careful not to follow the print keyword with a left parenthesis
401 unless you want the corresponding right parenthesis to terminate the
402 arguments to the print\*(--interpose a + or put parens around all the arguments.
403 .Ip "printf(FILEHANDLE LIST)" 8 10
405 .Ip "printf FILEHANDLE LIST" 8
407 Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
408 .Ip "push(ARRAY,LIST)" 8 7
409 Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
410 onto the end of ARRAY.
411 The length of ARRAY increases by the length of LIST.
412 Has the same effect as
416 $ARRAY[++$#ARRAY] = $value;
420 but is more efficient.
423 These are not really functions, but simply syntactic sugar to let you
424 avoid putting too many backslashes into quoted strings.
425 The q operator is a generalized single quote, and the qq operator a
426 generalized double quote.
427 Any non-alphanumeric delimiter can be used in place of /, including newline.
428 If the delimiter is an opening bracket or parenthesis, the final delimiter
429 will be the corresponding closing bracket or parenthesis.
430 (Embedded occurrences of the closing bracket need to be backslashed as usual.)
435 $foo = q!I said, "You said, \'She said it.\'"!;
436 $bar = q(\'This is it.\');
438 *** The previous line contains the naughty word "$&".\en
439 if /(ibm|apple|awk)/; # :-)
445 Returns a random fractional number between 0 and the value of EXPR.
446 (EXPR should be positive.)
447 If EXPR is omitted, returns a value between 0 and 1.
449 .Ip "read(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
450 .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
451 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
453 Returns the number of bytes actually read, or undef if there was an error.
454 SCALAR will be grown or shrunk to the length actually read.
455 An OFFSET may be specified to place the read data at some other place
456 than the beginning of the string.
457 This call is actually implemented in terms of stdio's fread call. To get
458 a true read system call, see sysread.
459 .Ip "readdir(DIRHANDLE)" 8 3
460 .Ip "readdir DIRHANDLE" 8
461 Returns the next directory entry for a directory opened by opendir().
462 If used in an array context, returns all the rest of the entries in the
464 If there are no more entries, returns an undefined value in a scalar context
465 or a null list in an array context.
466 .Ip "readlink(EXPR)" 8 6
467 .Ip "readlink EXPR" 8
468 Returns the value of a symbolic link, if symbolic links are implemented.
469 If not, gives a fatal error.
470 If there is some system error, returns the undefined value and sets $! (errno).
471 If EXPR is omitted, uses $_.
472 .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
473 Receives a message on a socket.
474 Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
476 Returns the address of the sender, or the undefined value if there's an error.
477 SCALAR will be grown or shrunk to the length actually read.
478 Takes the same flags as the system call of the same name.
483 command restarts the loop block without evaluating the conditional again.
486 block, if any, is not executed.
487 If the LABEL is omitted, the command refers to the innermost enclosing loop.
488 This command is normally used by programs that want to lie to themselves
489 about what was just input:
493 # a simpleminded Pascal comment stripper
494 # (warning: assumes no { or } in strings)
495 line: while (<STDIN>) {
496 while (s|\|({.*}.*\|){.*}|$1 \||) {}
501 if (\|/\|}/\|) { # end of comment?
511 .Ip "rename(OLDNAME,NEWNAME)" 8 2
512 Changes the name of a file.
513 Returns 1 for success, 0 otherwise.
514 Will not work across filesystem boundaries.
515 .Ip "require(EXPR)" 8 6
518 Includes the library file specified by EXPR, or by $_ if EXPR is not supplied.
519 Has semantics similar to the following subroutine:
523 local($filename) = @_;
524 return 1 if $INC{$filename};
525 local($realfilename,$result);
527 foreach $prefix (@INC) {
528 $realfilename = "$prefix/$filename";
529 if (-f $realfilename) {
530 $result = do $realfilename;
534 die "Can't find $filename in \e@INC";
537 die "$filename did not return true value" unless $result;
538 $INC{$filename} = $realfilename;
543 Note that the file will not be included twice under the same specified name.
544 .Ip "reset(EXPR)" 8 6
549 block at the end of a loop to clear variables and reset ?? searches
550 so that they work again.
551 The expression is interpreted as a list of single characters (hyphens allowed
553 All variables and arrays beginning with one of those letters are reset to
554 their pristine state.
555 If the expression is omitted, one-match searches (?pattern?) are reset to
557 Only resets variables or searches in the current package.
563 reset \'X\'; \h'|2i'# reset all X variables
564 reset \'a\-z\';\h'|2i'# reset lower case variables
565 reset; \h'|2i'# just reset ?? searches
568 Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
571 The use of reset on dbm associative arrays does not change the dbm file.
572 (It does, however, flush any entries cached by perl, which may be useful if
573 you are sharing the dbm file.
574 Then again, maybe not.)
575 .Ip "return LIST" 8 3
576 Returns from a subroutine with the value specified.
577 (Note that a subroutine can automatically return
578 the value of the last expression evaluated.
579 That's the preferred method\*(--use of an explicit
582 .Ip "reverse(LIST)" 8 4
584 In an array context, returns an array value consisting of the elements
585 of LIST in the opposite order.
586 In a scalar context, returns a string value consisting of the bytes of
587 the first element of LIST in the opposite order.
588 .Ip "rewinddir(DIRHANDLE)" 8 5
589 .Ip "rewinddir DIRHANDLE" 8
590 Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
591 .Ip "rindex(STR,SUBSTR,POSITION)" 8 6
592 .Ip "rindex(STR,SUBSTR)" 8 4
593 Works just like index except that it
594 returns the position of the LAST occurrence of SUBSTR in STR.
595 If POSITION is specified, returns the last occurrence at or before that
597 .Ip "rmdir(FILENAME)" 8 4
598 .Ip "rmdir FILENAME" 8
599 Deletes the directory specified by FILENAME if it is empty.
600 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
601 If FILENAME is omitted, uses $_.
602 .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
603 Searches a string for a pattern, and if found, replaces that pattern with the
604 replacement text and returns the number of substitutions made.
605 Otherwise it returns false (0).
606 The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
607 of the pattern are to be replaced.
608 The \*(L"i\*(R" is also optional, and if present, indicates that matching
609 is to be done in a case-insensitive manner.
610 The \*(L"e\*(R" is likewise optional, and if present, indicates that
611 the replacement string is to be evaluated as an expression rather than just
612 as a double-quoted string.
613 Any non-alphanumeric delimiter may replace the slashes;
614 if single quotes are used, no
615 interpretation is done on the replacement string (the e modifier overrides
616 this, however); if backquotes are used, the replacement string is a command
617 to execute whose output will be used as the actual replacement text.
618 If no string is specified via the =~ or !~ operator,
619 the $_ string is searched and modified.
620 (The string specified with =~ must be a scalar variable, an array element,
621 or an assignment to one of those, i.e. an lvalue.)
622 If the pattern contains a $ that looks like a variable rather than an
623 end-of-string test, the variable will be interpolated into the pattern at
625 If you only want the pattern compiled once the first time the variable is
626 interpolated, add an \*(L"o\*(R" at the end.
627 See also the section on regular expressions.
631 s/\|\e\|bgreen\e\|b/mauve/g; # don't change wintergreen
633 $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
635 s/Login: $foo/Login: $bar/; # run-time pattern
637 ($foo = $bar) =~ s/bar/foo/;
640 s/\ed+/$&*2/e; # yields \*(L'abc246xyz\*(R'
641 s/\ed+/sprintf("%5d",$&)/e; # yields \*(L'abc 246xyz\*(R'
642 s/\ew/$& x 2/eg; # yields \*(L'aabbcc 224466xxyyzz\*(R'
644 s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/; # reverse 1st two fields
647 (Note the use of $ instead of \|\e\| in the last example. See section
648 on regular expressions.)
649 .Ip "scalar(EXPR)" 8 3
650 Forces EXPR to be interpreted in a scalar context and returns the value
652 .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
653 Randomly positions the file pointer for FILEHANDLE, just like the fseek()
655 FILEHANDLE may be an expression whose value gives the name of the filehandle.
656 Returns 1 upon success, 0 otherwise.
657 .Ip "seekdir(DIRHANDLE,POS)" 8 3
658 Sets the current position for the readdir() routine on DIRHANDLE.
659 POS must be a value returned by telldir().
660 Has the same caveats about possible directory compaction as the corresponding
661 system library routine.
662 .Ip "select(FILEHANDLE)" 8 3
664 Returns the currently selected filehandle.
665 Sets the current default filehandle for output, if FILEHANDLE is supplied.
666 This has two effects: first, a
670 without a filehandle will default to this FILEHANDLE.
671 Second, references to variables related to output will refer to this output
673 For example, if you have to set the top of form format for more than
674 one output channel, you might do the following:
679 $^ = \'report1_top\';
681 $^ = \'report2_top\';
684 FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
688 $oldfh = select(STDERR); $| = 1; select($oldfh);
691 .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
692 This calls the select system call with the bitmasks specified, which can
693 be constructed using fileno() and vec(), along these lines:
696 $rin = $win = $ein = '';
697 vec($rin,fileno(STDIN),1) = 1;
698 vec($win,fileno(STDOUT),1) = 1;
702 If you want to select on many filehandles you might wish to write a subroutine:
706 local(@fhlist) = split(' ',$_[0]);
709 vec($bits,fileno($_),1) = 1;
713 $rin = &fhbits('STDIN TTY SOCK');
719 ($nfound,$timeleft) =
720 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
722 or to block until something becomes ready:
725 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
728 $nfound = select($rout=$rin, $wout=$win,
733 Any of the bitmasks can also be undef.
734 The timeout, if specified, is in seconds, which may be fractional.
735 NOTE: not all implementations are capable of returning the $timeleft.
736 If not, they always return $timeleft equal to the supplied $timeout.
737 .Ip "semctl(ID,SEMNUM,CMD,ARG)" 8 4
738 Calls the System V IPC function semctl. If CMD is &IPC_STAT or
739 &GETALL, then ARG must be a variable which will hold the returned
740 semid_ds structure or semaphore value array. Returns like ioctl: the
741 undefined value for error, "0 but true" for zero, or the actual return
743 .Ip "semget(KEY,NSEMS,SIZE,FLAGS)" 8 4
744 Calls the System V IPC function semget. Returns the semaphore id, or
745 the undefined value if there is an error.
746 .Ip "semop(KEY,OPSTRING)" 8 4
747 Calls the System V IPC function semop to perform semaphore operations
748 such as signaling and waiting. OPSTRING must be a packed array of
749 semop structures. Each semop structure can be generated with
750 \&'pack("sss", $semnum, $semop, $semflag)'. The number of semaphore
751 operations is implied by the length of OPSTRING. Returns true if
752 successful, or false if there is an error. As an example, the
753 following code waits on semaphore $semnum of semaphore id $semid:
756 $semop = pack("sss", $semnum, -1, 0);
757 die "Semaphore trouble: $!\en" unless semop($semid, $semop);
760 To signal the semaphore, replace "-1" with "1".
761 .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
762 .Ip "send(SOCKET,MSG,FLAGS)" 8
763 Sends a message on a socket.
764 Takes the same flags as the system call of the same name.
765 On unconnected sockets you must specify a destination to send TO.
766 Returns the number of characters sent, or the undefined value if
768 .Ip "setpgrp(PID,PGRP)" 8 4
769 Sets the current process group for the specified PID, 0 for the current
771 Will produce a fatal error if used on a machine that doesn't implement
773 .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
774 Sets the current priority for a process, a process group, or a user.
775 (See setpriority(2).)
776 Will produce a fatal error if used on a machine that doesn't implement
778 .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
779 Sets the socket option requested.
780 Returns undefined if there is an error.
781 OPTVAL may be specified as undef if you don't want to pass an argument.
782 .Ip "shift(ARRAY)" 8 6
785 Shifts the first value of the array off and returns it,
786 shortening the array by 1 and moving everything down.
787 If there are no elements in the array, returns the undefined value.
788 If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
789 array in subroutines.
790 (This is determined lexically.)
791 See also unshift(), push() and pop().
792 Shift() and unshift() do the same thing to the left end of an array that push()
793 and pop() do to the right end.
794 .Ip "shmctl(ID,CMD,ARG)" 8 4
795 Calls the System V IPC function shmctl. If CMD is &IPC_STAT, then ARG
796 must be a variable which will hold the returned shmid_ds structure.
797 Returns like ioctl: the undefined value for error, "0 but true" for
798 zero, or the actual return value otherwise.
799 .Ip "shmget(KEY,SIZE,FLAGS)" 8 4
800 Calls the System V IPC function shmget. Returns the shared memory
801 segment id, or the undefined value if there is an error.
802 .Ip "shmread(ID,VAR,POS,SIZE)" 8 4
803 .Ip "shmwrite(ID,STRING,POS,SIZE)" 8
804 Reads or writes the System V shared memory segment ID starting at
805 position POS for size SIZE by attaching to it, copying in/out, and
806 detaching from it. When reading, VAR must be a variable which
807 will hold the data read. When writing, if STRING is too long,
808 only SIZE bytes are used; if STRING is too short, nulls are
809 written to fill out SIZE bytes. Return true if successful, or
810 false if there is an error.
811 .Ip "shutdown(SOCKET,HOW)" 8 3
812 Shuts down a socket connection in the manner indicated by HOW, which has
813 the same interpretation as in the system call of the same name.
816 Returns the sine of EXPR (expressed in radians).
817 If EXPR is omitted, returns sine of $_.
818 .Ip "sleep(EXPR)" 8 6
821 Causes the script to sleep for EXPR seconds, or forever if no EXPR.
822 May be interrupted by sending the process a SIGALARM.
823 Returns the number of seconds actually slept.
824 .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
825 Opens a socket of the specified kind and attaches it to filehandle SOCKET.
826 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
828 You may need to run h2ph on sys/socket.h to get the proper values handy
829 in a perl library file.
830 Return true if successful.
831 See the example in the section on Interprocess Communication.
832 .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
833 Creates an unnamed pair of sockets in the specified domain, of the specified
835 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
837 If unimplemented, yields a fatal error.
838 Return true if successful.
839 .Ip "sort(SUBROUTINE LIST)" 8 9
841 .Ip "sort SUBROUTINE LIST" 8
843 Sorts the LIST and returns the sorted array value.
844 Nonexistent values of arrays are stripped out.
845 If SUBROUTINE is omitted, sorts in standard string comparison order.
846 If SUBROUTINE is specified, gives the name of a subroutine that returns
847 an integer less than, equal to, or greater than 0,
848 depending on how the elements of the array are to be ordered.
849 In the interests of efficiency the normal calling code for subroutines
850 is bypassed, with the following effects: the subroutine may not be a recursive
851 subroutine, and the two elements to be compared are passed into the subroutine
852 not via @_ but as $a and $b (see example below).
853 They are passed by reference so don't modify $a and $b.
854 SUBROUTINE may be a scalar variable name, in which case the value provides
855 the name of the subroutine to use.
861 $age{$a} - $age{$b}; # presuming integers
863 @sortedclass = sort byage @class;
866 sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
867 @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
868 @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
870 # prints AbelCaincatdogx
871 print sort reverse @harry;
872 # prints xdogcatCainAbel
873 print sort @george, \'to\', @harry;
874 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
877 .Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
878 .Ip "splice(ARRAY,OFFSET,LENGTH)" 8
879 .Ip "splice(ARRAY,OFFSET)" 8
880 Removes the elements designated by OFFSET and LENGTH from an array, and
881 replaces them with the elements of LIST, if any.
882 Returns the elements removed from the array.
883 The array grows or shrinks as necessary.
884 If LENGTH is omitted, removes everything from OFFSET onward.
885 The following equivalencies hold (assuming $[ == 0):
888 push(@a,$x,$y)\h'|3.5i'splice(@a,$#a+1,0,$x,$y)
889 pop(@a)\h'|3.5i'splice(@a,-1)
890 shift(@a)\h'|3.5i'splice(@a,0,1)
891 unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
892 $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
894 Example, assuming array lengths are passed before arrays:
896 sub aeq { # compare two array values
897 local(@a) = splice(@_,0,shift);
898 local(@b) = splice(@_,0,shift);
899 return 0 unless @a == @b; # same len?
901 return 0 if pop(@a) ne pop(@b);
905 if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
908 .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
909 .Ip "split(/PATTERN/,EXPR)" 8 8
910 .Ip "split(/PATTERN/)" 8
912 Splits a string into an array of strings, and returns it.
913 (If not in an array context, returns the number of fields found and splits
915 (In an array context, you can force the split into @_
916 by using ?? as the pattern delimiters, but it still returns the array value.))
917 If EXPR is omitted, splits the $_ string.
918 If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
919 Anything matching PATTERN is taken to be a delimiter separating the fields.
920 (Note that the delimiter may be longer than one character.)
921 If LIMIT is specified, splits into no more than that many fields (though it
922 may split into fewer).
923 If LIMIT is unspecified, trailing null fields are stripped (which
924 potential users of pop() would do well to remember).
925 A pattern matching the null string (not to be confused with a null pattern //,
926 which is just one member of the set of patterns matching a null string)
927 will split the value of EXPR into separate characters at each point it
932 print join(\':\', split(/ */, \'hi there\'));
935 produces the output \*(L'h:i:t:h:e:r:e\*(R'.
937 The LIMIT parameter can be used to partially split a line
940 ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
943 (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
944 larger than the number of variables in the list, to avoid unnecessary work.
945 For the list above LIMIT would have been 4 by default.
946 In time critical applications it behooves you not to split into
947 more fields than you really need.)
949 If the PATTERN contains parentheses, additional array elements are created
950 from each matching substring in the delimiter.
952 split(/([,-])/,"1-10,20");
954 produces the array value
958 The pattern /PATTERN/ may be replaced with an expression to specify patterns
959 that vary at runtime.
960 (To do runtime compilation only once, use /$variable/o.)
961 As a special case, specifying a space (\'\ \') will split on white space
962 just as split with no arguments does, but leading white space does NOT
963 produce a null first field.
964 Thus, split(\'\ \') can be used to emulate
966 default behavior, whereas
967 split(/\ /) will give you as many null initial fields as there are
974 open(passwd, \'/etc/passwd\');
977 ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
980 ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
981 = split(\|/\|:\|/\|);
987 (Note that $shell above will still have a newline on it. See chop().)
990 .Ip "sprintf(FORMAT,LIST)" 8 4
991 Returns a string formatted by the usual printf conventions.
992 The * character is not supported.
995 Return the square root of EXPR.
996 If EXPR is omitted, returns square root of $_.
997 .Ip "srand(EXPR)" 8 4
999 Sets the random number seed for the
1002 If EXPR is omitted, does srand(time).
1003 .Ip "stat(FILEHANDLE)" 8 8
1004 .Ip "stat FILEHANDLE" 8
1006 .Ip "stat SCALARVARIABLE" 8
1007 Returns a 13-element array giving the statistics for a file, either the file
1008 opened via FILEHANDLE, or named by EXPR.
1009 Typically used as follows:
1013 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
1014 $atime,$mtime,$ctime,$blksize,$blocks)
1018 If stat is passed the special filehandle consisting of an underline,
1019 no stat is done, but the current contents of the stat structure from
1020 the last stat or filetest are returned.
1025 if (-x $file && (($d) = stat(_)) && $d < 0) {
1026 print "$file is executable NFS file\en";
1030 .Ip "study(SCALAR)" 8 6
1031 .Ip "study SCALAR" 8
1033 Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
1034 doing many pattern matches on the string before it is next modified.
1035 This may or may not save time, depending on the nature and number of patterns
1036 you are searching on, and on the distribution of character frequencies in
1037 the string to be searched\*(--you probably want to compare runtimes with and
1038 without it to see which runs faster.
1039 Those loops which scan for many short constant strings (including the constant
1040 parts of more complex patterns) will benefit most.
1041 You may have only one study active at a time\*(--if you study a different
1042 scalar the first is \*(L"unstudied\*(R".
1043 (The way study works is this: a linked list of every character in the string
1044 to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
1046 From each search string, the rarest character is selected, based on some
1047 static frequency tables constructed from some C programs and English text.
1048 Only those places that contain this \*(L"rarest\*(R" character are examined.)
1050 For example, here is a loop which inserts index producing entries before any line
1051 containing a certain pattern:
1057 print ".IX foo\en" if /\ebfoo\eb/;
1058 print ".IX bar\en" if /\ebbar\eb/;
1059 print ".IX blurfl\en" if /\ebblurfl\eb/;
1065 In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
1066 will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
1067 In general, this is a big win except in pathological cases.
1068 The only question is whether it saves you more time than it took to build
1069 the linked list in the first place.
1071 Note that if you have to look for strings that you don't know till runtime,
1072 you can build an entire loop as a string and eval that to avoid recompiling
1073 all your patterns all the time.
1074 Together with setting $/ to input entire files as one record, this can
1075 be very fast, often faster than specialized programs like fgrep.
1076 The following scans a list of files (@files)
1077 for a list of words (@words), and prints out the names of those files that
1082 $search = \'while (<>) { study;\';
1083 foreach $word (@words) {
1084 $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
1088 $/ = "\e177"; # something that doesn't occur
1089 eval $search; # this screams
1090 $/ = "\en"; # put back to normal input delim
1091 foreach $file (sort keys(%seen)) {
1096 .Ip "substr(EXPR,OFFSET,LEN)" 8 2
1097 .Ip "substr(EXPR,OFFSET)" 8 2
1098 Extracts a substring out of EXPR and returns it.
1099 First character is at offset 0, or whatever you've set $[ to.
1100 If OFFSET is negative, starts that far from the end of the string.
1101 If LEN is omitted, returns everything to the end of the string.
1102 You can use the substr() function as an lvalue, in which case EXPR must
1104 If you assign something shorter than LEN, the string will shrink, and
1105 if you assign something longer than LEN, the string will grow to accommodate it.
1106 To keep the string the same length you may need to pad or chop your value using
1108 .Ip "symlink(OLDFILE,NEWFILE)" 8 2
1109 Creates a new filename symbolically linked to the old filename.
1110 Returns 1 for success, 0 otherwise.
1111 On systems that don't support symbolic links, produces a fatal error at
1113 To check for that, use eval:
1116 $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
1119 .Ip "syscall(LIST)" 8 6
1120 .Ip "syscall LIST" 8
1121 Calls the system call specified as the first element of the list, passing
1122 the remaining elements as arguments to the system call.
1123 If unimplemented, produces a fatal error.
1124 The arguments are interpreted as follows: if a given argument is numeric,
1125 the argument is passed as an int.
1126 If not, the pointer to the string value is passed.
1127 You are responsible to make sure a string is pre-extended long enough
1128 to receive any result that might be written into a string.
1129 If your integer arguments are not literals and have never been interpreted
1130 in a numeric context, you may need to add 0 to them to force them to look
1134 require 'syscall.ph'; # may need to run h2ph
1135 syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
1138 .Ip "sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
1139 .Ip "sysread(FILEHANDLE,SCALAR,LENGTH)" 8 5
1140 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
1141 FILEHANDLE, using the system call read(2).
1142 It bypasses stdio, so mixing this with other kinds of reads may cause
1144 Returns the number of bytes actually read, or undef if there was an error.
1145 SCALAR will be grown or shrunk to the length actually read.
1146 An OFFSET may be specified to place the read data at some other place
1147 than the beginning of the string.
1148 .Ip "system(LIST)" 8 6
1150 Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
1151 is done first, and the parent process waits for the child process to complete.
1152 Note that argument processing varies depending on the number of arguments.
1153 The return value is the exit status of the program as returned by the wait()
1155 To get the actual exit value divide by 256.
1158 .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
1159 .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH)" 8 5
1160 Attempts to write LENGTH bytes of data from variable SCALAR to the specified
1161 FILEHANDLE, using the system call write(2).
1162 It bypasses stdio, so mixing this with prints may cause
1164 Returns the number of bytes actually written, or undef if there was an error.
1165 An OFFSET may be specified to place the read data at some other place
1166 than the beginning of the string.
1167 .Ip "tell(FILEHANDLE)" 8 6
1168 .Ip "tell FILEHANDLE" 8 6
1170 Returns the current file position for FILEHANDLE.
1171 FILEHANDLE may be an expression whose value gives the name of the actual
1173 If FILEHANDLE is omitted, assumes the file last read.
1174 .Ip "telldir(DIRHANDLE)" 8 5
1175 .Ip "telldir DIRHANDLE" 8
1176 Returns the current position of the readdir() routines on DIRHANDLE.
1177 Value may be given to seekdir() to access a particular location in
1179 Has the same caveats about possible directory compaction as the corresponding
1180 system library routine.
1182 Returns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970.
1183 Suitable for feeding to gmtime() and localtime().
1185 Returns a four-element array giving the user and system times, in seconds, for this
1186 process and the children of this process.
1188 ($user,$system,$cuser,$csystem) = times;
1190 .Ip "tr/SEARCHLIST/REPLACEMENTLIST/cds" 8 5
1191 .Ip "y/SEARCHLIST/REPLACEMENTLIST/cds" 8
1192 Translates all occurrences of the characters found in the search list with
1193 the corresponding character in the replacement list.
1194 It returns the number of characters replaced or deleted.
1195 If no string is specified via the =~ or !~ operator,
1196 the $_ string is translated.
1197 (The string specified with =~ must be a scalar variable, an array element,
1198 or an assignment to one of those, i.e. an lvalue.)
1203 is provided as a synonym for
1206 If the c modifier is specified, the SEARCHLIST character set is complemented.
1207 If the d modifier is specified, any characters specified by SEARCHLIST that
1208 are not found in REPLACEMENTLIST are deleted.
1209 (Note that this is slightly more flexible than the behavior of some
1211 programs, which delete anything they find in the SEARCHLIST, period.)
1212 If the s modifier is specified, sequences of characters that were translated
1213 to the same character are squashed down to 1 instance of the character.
1215 If the d modifier was used, the REPLACEMENTLIST is always interpreted exactly
1217 Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST,
1218 the final character is replicated till it is long enough.
1219 If the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
1220 This latter is useful for counting characters in a class, or for squashing
1221 character sequences in a class.
1226 $ARGV[1] \|=~ \|y/A\-Z/a\-z/; \h'|3i'# canonicalize to lower case
1228 $cnt = tr/*/*/; \h'|3i'# count the stars in $_
1230 $cnt = tr/0\-9//; \h'|3i'# count the digits in $_
1232 tr/a\-zA\-Z//s; \h'|3i'# bookkeeper \-> bokeper
1234 ($HOST = $host) =~ tr/a\-z/A\-Z/;
1236 y/a\-zA\-Z/ /cs; \h'|3i'# change non-alphas to single space
1238 tr/\e200\-\e377/\e0\-\e177/;\h'|3i'# delete 8th bit
1241 .Ip "truncate(FILEHANDLE,LENGTH)" 8 4
1242 .Ip "truncate(EXPR,LENGTH)" 8
1243 Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified
1245 Produces a fatal error if truncate isn't implemented on your system.
1246 .Ip "umask(EXPR)" 8 4
1249 Sets the umask for the process and returns the old one.
1250 If EXPR is omitted, merely returns current umask.
1251 .Ip "undef(EXPR)" 8 6
1254 Undefines the value of EXPR, which must be an lvalue.
1255 Use only on a scalar value, an entire array, or a subroutine name (using &).
1256 (Undef will probably not do what you expect on most predefined variables or
1258 Always returns the undefined value.
1259 You can omit the EXPR, in which case nothing is undefined, but you still
1260 get an undefined value that you could, for instance, return from a subroutine.
1266 undef $bar{'blurfl'};
1270 return (wantarray ? () : undef) if $they_blew_it;
1273 .Ip "unlink(LIST)" 8 4
1275 Deletes a list of files.
1276 Returns the number of files successfully deleted.
1280 $cnt = unlink \'a\', \'b\', \'c\';
1285 Note: unlink will not delete directories unless you are superuser and the
1289 Even if these conditions are met, be warned that unlinking a directory
1290 can inflict damage on your filesystem.
1292 .Ip "unpack(TEMPLATE,EXPR)" 8 4
1293 Unpack does the reverse of pack: it takes a string representing
1294 a structure and expands it out into an array value, returning the array
1296 (In a scalar context, it merely returns the first value produced.)
1297 The TEMPLATE has the same format as in the pack function.
1298 Here's a subroutine that does substring:
1303 local($what,$where,$howmuch) = @_;
1304 unpack("x$where a$howmuch", $what);
1310 sub ord { unpack("c",$_[0]); }
1313 In addition, you may prefix a field with a %<number> to indicate that
1314 you want a <number>-bit checksum of the items instead of the items themselves.
1315 Default is a 16-bit checksum.
1316 For example, the following computes the same number as the System V sum program:
1321 $checksum += unpack("%16C*", $_);
1326 .Ip "unshift(ARRAY,LIST)" 8 4
1327 Does the opposite of a
1329 Or the opposite of a
1331 depending on how you look at it.
1332 Prepends list to the front of the array, and returns the number of elements
1336 unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
1339 .Ip "utime(LIST)" 8 2
1340 .Ip "utime LIST" 8 2
1341 Changes the access and modification times on each file of a list of files.
1342 The first two elements of the list must be the NUMERICAL access and
1343 modification times, in that order.
1344 Returns the number of files successfully changed.
1345 The inode modification time of each file is set to the current time.
1346 Example of a \*(L"touch\*(R" command:
1352 utime $now, $now, @ARGV;
1355 .Ip "values(ASSOC_ARRAY)" 8 6
1356 .Ip "values ASSOC_ARRAY" 8
1357 Returns a normal array consisting of all the values of the named associative
1359 The values are returned in an apparently random order, but it is the same order
1360 as either the keys() or each() function would produce on the same array.
1361 See also keys() and each().
1362 .Ip "vec(EXPR,OFFSET,BITS)" 8 2
1363 Treats a string as a vector of unsigned integers, and returns the value
1364 of the bitfield specified.
1365 May also be assigned to.
1366 BITS must be a power of two from 1 to 32.
1368 Vectors created with vec() can also be manipulated with the logical operators
1370 which will assume a bit vector operation is desired when both operands are
1372 This interpretation is not enabled unless there is at least one vec() in
1373 your program, to protect older programs.
1375 To transform a bit vector into a string or array of 0's and 1's, use these:
1378 $bits = unpack("b*", $vector);
1379 @bits = split(//, unpack("b*", $vector));
1382 If you know the exact length in bits, it can be used in place of the *.
1384 Waits for a child process to terminate and returns the pid of the deceased
1385 process, or -1 if there are no child processes.
1386 The status is returned in $?.
1387 .Ip "waitpid(PID,FLAGS)" 8 6
1388 Waits for a particular child process to terminate and returns the pid of the deceased
1389 process, or -1 if there is no such child process.
1390 The status is returned in $?.
1394 require "sys/wait.h";
1396 waitpid(-1,&WNOHANG);
1399 then you can do a non-blocking wait for any process. Non-blocking wait
1400 is only available on machines supporting either the
1405 However, waiting for a particular pid with FLAGS of 0 is implemented
1406 everywhere. (Perl emulates the system call by remembering the status
1407 values of processes that have exited but have not been harvested by the
1410 Returns true if the context of the currently executing subroutine
1411 is looking for an array value.
1412 Returns false if the context is looking for a scalar.
1415 return wantarray ? () : undef;
1418 .Ip "warn(LIST)" 8 4
1420 Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
1421 .Ip "write(FILEHANDLE)" 8 6
1424 Writes a formatted record (possibly multi-line) to the specified file,
1425 using the format associated with that file.
1426 By default the format for a file is the one having the same name is the
1427 filehandle, but the format for the current output channel (see
1429 may be set explicitly
1430 by assigning the name of the format to the $~ variable.
1432 Top of form processing is handled automatically:
1433 if there is insufficient room on the current page for the formatted
1434 record, the page is advanced by writing a form feed,
1435 a special top-of-page format is used
1436 to format the new page header, and then the record is written.
1437 By default the top-of-page format is \*(L"top\*(R", but it
1439 format of your choice by assigning the name to the $^ variable.
1440 The number of lines remaining on the current page is in variable $-, which
1441 can be set to 0 to force a new page.
1443 If FILEHANDLE is unspecified, output goes to the current default output channel,
1446 but may be changed by the
1449 If the FILEHANDLE is an EXPR, then the expression is evaluated and the
1450 resulting string is used to look up the name of the FILEHANDLE at run time.
1451 For more on formats, see the section on formats later on.
1453 Note that write is NOT the opposite of read.