1 ''' Beginning of part 3
2 ''' $Header: perl.man.3,v 3.0.1.5 90/03/12 16:52:21 lwall Locked $
4 ''' $Log: perl.man.3,v $
5 ''' Revision 3.0.1.5 90/03/12 16:52:21 lwall
6 ''' patch13: documented that print $filehandle &foo is ambiguous
7 ''' patch13: added splice operator: @oldelems = splice(@array,$offset,$len,LIST)
9 ''' Revision 3.0.1.4 90/02/28 18:00:09 lwall
10 ''' patch9: added pipe function
11 ''' patch9: documented how to handle arbitrary weird characters in filenames
12 ''' patch9: documented the unflushed buffers problem on piped opens
13 ''' patch9: documented how to force top of page
15 ''' Revision 3.0.1.3 89/12/21 20:10:12 lwall
16 ''' patch7: documented that s`pat`repl` does command substitution on replacement
17 ''' patch7: documented that $timeleft from select() is likely not implemented
19 ''' Revision 3.0.1.2 89/11/17 15:31:05 lwall
20 ''' patch5: fixed some manual typos and indent problems
21 ''' patch5: added warning about print making an array context
23 ''' Revision 3.0.1.1 89/11/11 04:45:06 lwall
24 ''' patch2: made some line breaks depend on troff vs. nroff
26 ''' Revision 3.0 89/10/18 15:21:46 lwall
35 statement in C; it starts the next iteration of the loop:
39 line: while (<STDIN>) {
40 next line if /\|^#/; # discard comments
45 Note that if there were a
47 block on the above, it would get executed even on discarded lines.
48 If the LABEL is omitted, the command refers to the innermost enclosing loop.
51 Returns the decimal value of EXPR interpreted as an octal string.
52 (If EXPR happens to start off with 0x, interprets it as a hex string instead.)
53 The following will handle decimal, octal and hex in the standard notation:
56 $val = oct($val) if $val =~ /^0/;
59 If EXPR is omitted, uses $_.
60 .Ip "open(FILEHANDLE,EXPR)" 8 8
61 .Ip "open(FILEHANDLE)" 8
62 .Ip "open FILEHANDLE" 8
63 Opens the file whose filename is given by EXPR, and associates it with
65 If FILEHANDLE is an expression, its value is used as the name of the
66 real filehandle wanted.
67 If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
68 contains the filename.
69 If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
71 If the filename begins with \*(L">\*(R", the file is opened for output.
72 If the filename begins with \*(L">>\*(R", the file is opened for appending.
73 (You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
74 want both read and write access to the file.)
75 If the filename begins with \*(L"|\*(R", the filename is interpreted
76 as a command to which output is to be piped, and if the filename ends
77 with a \*(L"|\*(R", the filename is interpreted as command which pipes
79 (You may not have a command that pipes both in and out.)
82 and opening \'>\-\' opens
84 Open returns non-zero upon success, the undefined value otherwise.
85 If the open involved a pipe, the return value happens to be the pid
92 open article || die "Can't find article $article: $!\en";
93 while (<article>) {\|.\|.\|.
96 open(LOG, \'>>/usr/spool/news/twitlog\'\|); # (log is reserved)
99 open(LOG, \'>>/usr/spool/news/twitlog\'\|);
104 open(article, "caesar <$article |"\|); # decrypt article
107 open(article, "caesar <$article |"\|);
112 open(extract, "|sort >/tmp/Tmp$$"\|); # $$ is our process#
115 open(extract, "|sort >/tmp/Tmp$$"\|);
120 # process argument list of files along with any includes
122 foreach $file (@ARGV) {
123 do process($file, \'fh00\'); # no pun intended
127 local($filename, $input) = @_;
128 $input++; # this is a string increment
129 unless (open($input, $filename)) {
130 print STDERR "Can't open $filename: $!\en";
134 while (<$input>) { # note the use of indirection
137 while (<$input>) { # note use of indirection
139 if (/^#include "(.*)"/) {
140 do process($1, $input);
148 You may also, in the Bourne shell tradition, specify an EXPR beginning
149 with \*(L">&\*(R", in which case the rest of the string
150 is interpreted as the name of a filehandle
151 (or file descriptor, if numeric) which is to be duped and opened.
152 You may use & after >, >>, <, +>, +>> and +<.
153 The mode you specify should match the mode of the original filehandle.
154 Here is a script that saves, redirects, and restores
162 open(SAVEOUT, ">&STDOUT");
163 open(SAVEERR, ">&STDERR");
165 open(STDOUT, ">foo.out") || die "Can't redirect stdout";
166 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
168 select(STDERR); $| = 1; # make unbuffered
169 select(STDOUT); $| = 1; # make unbuffered
171 print STDOUT "stdout 1\en"; # this works for
172 print STDERR "stderr 1\en"; # subprocesses too
177 open(STDOUT, ">&SAVEOUT");
178 open(STDERR, ">&SAVEERR");
180 print STDOUT "stdout 2\en";
181 print STDERR "stderr 2\en";
184 If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
185 then there is an implicit fork done, and the return value of open
186 is the pid of the child within the parent process, and 0 within the child
188 (Use defined($pid) to determine if the open was successful.)
189 The filehandle behaves normally for the parent, but i/o to that
190 filehandle is piped from/to the
192 of the child process.
193 In the child process the filehandle isn't opened\*(--i/o happens from/to
198 Typically this is used like the normal piped open when you want to exercise
199 more control over just how the pipe command gets executed, such as when
200 you are running setuid, and don't want to have to scan shell commands
202 The following pairs are equivalent:
206 open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
207 open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
209 open(FOO, "cat \-n $file|");
210 open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
213 Explicitly closing any piped filehandle causes the parent process to wait for the
214 child to finish, and returns the status value in $?.
215 Note: on any operation which may do a fork,
216 unflushed buffers remain unflushed in both
217 processes, which means you may need to set $| to
218 avoid duplicate output.
220 The filename that is passed to open will have leading and trailing
222 In order to open a file with arbitrary weird characters in it, it's necessary
223 to protect any leading and trailing whitespace thusly:
227 $file =~ s#^(\es)#./$1#;
228 open(FOO, "< $file\e0");
231 .Ip "opendir(DIRHANDLE,EXPR)" 8 3
232 Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
233 rewinddir() and closedir().
234 Returns true if successful.
235 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
238 Returns the ascii value of the first character of EXPR.
239 If EXPR is omitted, uses $_.
240 .Ip "pack(TEMPLATE,LIST)" 8 4
241 Takes an array or list of values and packs it into a binary structure,
242 returning the string containing the structure.
243 The TEMPLATE is a sequence of characters that give the order and type
244 of values, as follows:
247 A An ascii string, will be space padded.
248 a An ascii string, will be null padded.
249 c A native char value.
250 C An unsigned char value.
251 s A signed short value.
252 S An unsigned short value.
253 i A signed integer value.
254 I An unsigned integer value.
255 l A signed long value.
256 L An unsigned long value.
257 n A short in \*(L"network\*(R" order.
258 N A long in \*(L"network\*(R" order.
259 p A pointer to a string.
263 Each letter may optionally be followed by a number which gives a repeat
265 With all types except "a" and "A" the pack function will gobble up that many values
267 The "a" and "A" types gobble just one value, but pack it as a string that long,
268 padding with nulls or spaces as necessary.
269 (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
273 $foo = pack("cccc",65,66,67,68);
275 $foo = pack("c4",65,66,67,68);
278 $foo = pack("ccxxcc",65,66,67,68);
279 # foo eq "AB\e0\e0CD"
281 $foo = pack("s2",1,2);
282 # "\e1\e0\e2\e0" on little-endian
283 # "\e0\e1\e0\e2" on big-endian
285 $foo = pack("a4","abcd","x","y","z");
288 $foo = pack("aaaa","abcd","x","y","z");
291 $foo = pack("a14","abcdefg");
292 # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
294 $foo = pack("i9pl", gmtime);
295 # a real struct tm (on my system anyway)
298 The same template may generally also be used in the unpack function.
299 .Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
300 Opens a pair of connected pipes like the corresponding system call.
301 Note that if you set up a loop of piped processes, deadlock can occur
302 unless you are very careful.
303 In addition, note that perl's pipes use stdio buffering, so you may need
304 to set $| to flush your WRITEHANDLE after each command, depending on
306 [Requires version 3.0 patchlevel 9.]
309 Pops and returns the last value of the array, shortening the array by 1.
310 Has the same effect as
313 $tmp = $ARRAY[$#ARRAY\-\|\-];
316 If there are no elements in the array, returns the undefined value.
317 .Ip "print(FILEHANDLE LIST)" 8 10
319 .Ip "print FILEHANDLE LIST" 8
322 Prints a string or a comma-separated list of strings.
323 Returns non-zero if successful.
324 FILEHANDLE may be a scalar variable name, in which case the variable contains
325 the name of the filehandle, thus introducing one level of indirection.
326 (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
327 misinterpreted as an operator unless you interpose a + or put parens around
329 If FILEHANDLE is omitted, prints by default to standard output (or to the
330 last selected output channel\*(--see select()).
331 If LIST is also omitted, prints $_ to
333 To set the default output channel to something other than
335 use the select operation.
336 Note that, because print takes a LIST, anything in the LIST is evaluated
337 in an array context, and any subroutine that you call will have one or more
338 of its expressions evaluated in an array context.
339 Also be careful not to follow the print keyword with a left parenthesis
340 unless you want the corresponding right parenthesis to terminate the
341 arguments to the print--interpose a + or put parens around all the arguments.
342 .Ip "printf(FILEHANDLE LIST)" 8 10
344 .Ip "printf FILEHANDLE LIST" 8
346 Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
347 .Ip "push(ARRAY,LIST)" 8 7
348 Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
349 onto the end of ARRAY.
350 The length of ARRAY increases by the length of LIST.
351 Has the same effect as
355 $ARRAY[++$#ARRAY] = $value;
359 but is more efficient.
362 These are not really functions, but simply syntactic sugar to let you
363 avoid putting too many backslashes into quoted strings.
364 The q operator is a generalized single quote, and the qq operator a
365 generalized double quote.
366 Any delimiter can be used in place of /, including newline.
367 If the delimiter is an opening bracket or parenthesis, the final delimiter
368 will be the corresponding closing bracket or parenthesis.
369 (Embedded occurrences of the closing bracket need to be backslashed as usual.)
374 $foo = q!I said, "You said, \'She said it.\'"!;
375 $bar = q(\'This is it.\');
377 *** The previous line contains the naughty word "$&".\en
378 if /(ibm|apple|awk)/; # :-)
384 Returns a random fractional number between 0 and the value of EXPR.
385 (EXPR should be positive.)
386 If EXPR is omitted, returns a value between 0 and 1.
388 .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
389 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
391 Returns the number of bytes actually read.
392 SCALAR will be grown or shrunk to the length actually read.
393 .Ip "readdir(DIRHANDLE)" 8 3
394 .Ip "readdir DIRHANDLE" 8
395 Returns the next directory entry for a directory opened by opendir().
396 If used in an array context, returns all the rest of the entries in the
398 If there are no more entries, returns an undefined value in a scalar context
399 or a null list in an array context.
400 .Ip "readlink(EXPR)" 8 6
401 .Ip "readlink EXPR" 8
402 Returns the value of a symbolic link, if symbolic links are implemented.
403 If not, gives a fatal error.
404 If there is some system error, returns the undefined value and sets $! (errno).
405 If EXPR is omitted, uses $_.
406 .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
407 Receives a message on a socket.
408 Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
410 Returns the address of the sender, or the undefined value if there's an error.
411 SCALAR will be grown or shrunk to the length actually read.
412 Takes the same flags as the system call of the same name.
417 command restarts the loop block without evaluating the conditional again.
420 block, if any, is not executed.
421 If the LABEL is omitted, the command refers to the innermost enclosing loop.
422 This command is normally used by programs that want to lie to themselves
423 about what was just input:
427 # a simpleminded Pascal comment stripper
428 # (warning: assumes no { or } in strings)
429 line: while (<STDIN>) {
430 while (s|\|({.*}.*\|){.*}|$1 \||) {}
435 if (\|/\|}/\|) { # end of comment?
445 .Ip "rename(OLDNAME,NEWNAME)" 8 2
446 Changes the name of a file.
447 Returns 1 for success, 0 otherwise.
448 Will not work across filesystem boundaries.
449 .Ip "reset(EXPR)" 8 6
454 block at the end of a loop to clear variables and reset ?? searches
455 so that they work again.
456 The expression is interpreted as a list of single characters (hyphens allowed
458 All variables and arrays beginning with one of those letters are reset to
459 their pristine state.
460 If the expression is omitted, one-match searches (?pattern?) are reset to
462 Only resets variables or searches in the current package.
468 reset \'X\'; \h'|2i'# reset all X variables
469 reset \'a\-z\';\h'|2i'# reset lower case variables
470 reset; \h'|2i'# just reset ?? searches
473 Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
476 The use of reset on dbm associative arrays does not change the dbm file.
477 (It does, however, flush any entries cached by perl, which may be useful if
478 you are sharing the dbm file.
479 Then again, maybe not.)
480 .Ip "return LIST" 8 3
481 Returns from a subroutine with the value specified.
482 (Note that a subroutine can automatically return
483 the value of the last expression evaluated.
484 That's the preferred method\*(--use of an explicit
487 .Ip "reverse(LIST)" 8 4
489 Returns an array value consisting of the elements of LIST in the opposite order.
490 .Ip "rewinddir(DIRHANDLE)" 8 5
491 .Ip "rewinddir DIRHANDLE" 8
492 Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
493 .Ip "rindex(STR,SUBSTR)" 8 4
494 Works just like index except that it
495 returns the position of the LAST occurrence of SUBSTR in STR.
496 .Ip "rmdir(FILENAME)" 8 4
497 .Ip "rmdir FILENAME" 8
498 Deletes the directory specified by FILENAME if it is empty.
499 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
500 If FILENAME is omitted, uses $_.
501 .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
502 Searches a string for a pattern, and if found, replaces that pattern with the
503 replacement text and returns the number of substitutions made.
504 Otherwise it returns false (0).
505 The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
506 of the pattern are to be replaced.
507 The \*(L"i\*(R" is also optional, and if present, indicates that matching
508 is to be done in a case-insensitive manner.
509 The \*(L"e\*(R" is likewise optional, and if present, indicates that
510 the replacement string is to be evaluated as an expression rather than just
511 as a double-quoted string.
512 Any delimiter may replace the slashes; if single quotes are used, no
513 interpretation is done on the replacement string (the e modifier overrides
514 this, however); if backquotes are used, the replacement string is a command
515 to execute whose output will be used as the actual replacement text.
516 If no string is specified via the =~ or !~ operator,
517 the $_ string is searched and modified.
518 (The string specified with =~ must be a scalar variable, an array element,
519 or an assignment to one of those, i.e. an lvalue.)
520 If the pattern contains a $ that looks like a variable rather than an
521 end-of-string test, the variable will be interpolated into the pattern at
523 If you only want the pattern compiled once the first time the variable is
524 interpolated, add an \*(L"o\*(R" at the end.
525 See also the section on regular expressions.
529 s/\|\e\|bgreen\e\|b/mauve/g; # don't change wintergreen
531 $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
533 s/Login: $foo/Login: $bar/; # run-time pattern
535 ($foo = $bar) =~ s/bar/foo/;
538 s/\ed+/$&*2/e; # yields \*(L'abc246xyz\*(R'
539 s/\ed+/sprintf("%5d",$&)/e; # yields \*(L'abc 246xyz\*(R'
540 s/\ew/$& x 2/eg; # yields \*(L'aabbcc 224466xxyyzz\*(R'
542 s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/; # reverse 1st two fields
545 (Note the use of $ instead of \|\e\| in the last example. See section
546 on regular expressions.)
547 .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
548 Randomly positions the file pointer for FILEHANDLE, just like the fseek()
550 FILEHANDLE may be an expression whose value gives the name of the filehandle.
551 Returns 1 upon success, 0 otherwise.
552 .Ip "seekdir(DIRHANDLE,POS)" 8 3
553 Sets the current position for the readdir() routine on DIRHANDLE.
554 POS must be a value returned by seekdir().
555 Has the same caveats about possible directory compaction as the corresponding
556 system library routine.
557 .Ip "select(FILEHANDLE)" 8 3
559 Returns the currently selected filehandle.
560 Sets the current default filehandle for output, if FILEHANDLE is supplied.
561 This has two effects: first, a
565 without a filehandle will default to this FILEHANDLE.
566 Second, references to variables related to output will refer to this output
568 For example, if you have to set the top of form format for more than
569 one output channel, you might do the following:
574 $^ = \'report1_top\';
576 $^ = \'report2_top\';
579 FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
583 $oldfh = select(STDERR); $| = 1; select($oldfh);
586 .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
587 This calls the select system call with the bitmasks specified, which can
588 be constructed using fileno() and vec(), along these lines:
591 $rin = $win = $ein = '';
592 vec($rin,fileno(STDIN),1) = 1;
593 vec($win,fileno(STDOUT),1) = 1;
597 If you want to select on many filehandles you might wish to write a subroutine:
601 local(@fhlist) = split(' ',$_[0]);
604 vec($bits,fileno($_),1) = 1;
608 $rin = &fhbits('STDIN TTY SOCK');
614 ($nfound,$timeleft) =
615 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
617 or to block until something becomes ready:
620 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
623 $nfound = select($rout=$rin, $wout=$win,
628 Any of the bitmasks can also be undef.
629 The timeout, if specified, is in seconds, which may be fractional.
630 NOTE: not all implementations are capable of returning the $timeleft.
631 If not, they always return $timeleft equal to the supplied $timeout.
632 .Ip "setpgrp(PID,PGRP)" 8 4
633 Sets the current process group for the specified PID, 0 for the current
635 Will produce a fatal error if used on a machine that doesn't implement
637 .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
638 .Ip "send(SOCKET,MSG,FLAGS)" 8
639 Sends a message on a socket.
640 Takes the same flags as the system call of the same name.
641 On unconnected sockets you must specify a destination to send TO.
642 Returns the number of characters sent, or the undefined value if
644 .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
645 Sets the current priority for a process, a process group, or a user.
646 (See setpriority(2).)
647 Will produce a fatal error if used on a machine that doesn't implement
649 .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
650 Sets the socket option requested.
651 Returns undefined if there is an error.
652 OPTVAL may be specified as undef if you don't want to pass an argument.
653 .Ip "shift(ARRAY)" 8 6
656 Shifts the first value of the array off and returns it,
657 shortening the array by 1 and moving everything down.
658 If there are no elements in the array, returns the undefined value.
659 If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
660 array in subroutines.
661 See also unshift(), push() and pop().
662 Shift() and unshift() do the same thing to the left end of an array that push()
663 and pop() do to the right end.
664 .Ip "shutdown(SOCKET,HOW)" 8 3
665 Shuts down a socket connection in the manner indicated by HOW, which has
666 the same interpretation as in the system call of the same name.
669 Returns the sine of EXPR (expressed in radians).
670 If EXPR is omitted, returns sine of $_.
671 .Ip "sleep(EXPR)" 8 6
674 Causes the script to sleep for EXPR seconds, or forever if no EXPR.
675 May be interrupted by sending the process a SIGALARM.
676 Returns the number of seconds actually slept.
677 .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
678 Opens a socket of the specified kind and attaches it to filehandle SOCKET.
679 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
681 You may need to run makelib on sys/socket.h to get the proper values handy
682 in a perl library file.
683 Return true if successful.
684 See the example in the section on Interprocess Communication.
685 .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
686 Creates an unnamed pair of sockets in the specified domain, of the specified
688 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
690 If unimplemented, yields a fatal error.
691 Return true if successful.
692 .Ip "sort(SUBROUTINE LIST)" 8 9
694 .Ip "sort SUBROUTINE LIST" 8
696 Sorts the LIST and returns the sorted array value.
697 Nonexistent values of arrays are stripped out.
698 If SUBROUTINE is omitted, sorts in standard string comparison order.
699 If SUBROUTINE is specified, gives the name of a subroutine that returns
700 an integer less than, equal to, or greater than 0,
701 depending on how the elements of the array are to be ordered.
702 In the interests of efficiency the normal calling code for subroutines
703 is bypassed, with the following effects: the subroutine may not be a recursive
704 subroutine, and the two elements to be compared are passed into the subroutine
705 not via @_ but as $a and $b (see example below).
706 They are passed by reference so don't modify $a and $b.
707 SUBROUTINE may be a scalar variable name, in which case the value provides
708 the name of the subroutine to use.
714 $age{$a} - $age{$b}; # presuming integers
716 @sortedclass = sort byage @class;
719 sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
720 @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
721 @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
723 # prints AbelCaincatdogx
724 print sort reverse @harry;
725 # prints xdogcatCainAbel
726 print sort @george, \'to\', @harry;
727 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
730 .Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
731 .Ip "splice(ARRAY,OFFSET,LENGTH)" 8
732 .Ip "splice(ARRAY,OFFSET)" 8
733 Removes the elements designated by OFFSET and LENGTH from an array, and
734 replaces them with the elements of LIST, if any.
735 Returns the elements removed from the array.
736 The array grows or shrinks as necessary.
737 If LENGTH is omitted, removes everything from OFFSET onward.
738 The following equivalencies hold (assuming $[ == 0):
741 push(@a,$x,$y)\h'|3.5i'splice(@a,$#x+1,0,$x,$y)
742 pop(@a)\h'|3.5i'splice(@a,-1)
743 shift(@a)\h'|3.5i'splice(@a,0,1)
744 unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
745 $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
747 Example, assuming array lengths are passed before arrays:
749 sub aeq { # compare two array values
750 local(@a) = splice(@_,0,shift);
751 local(@b) = splice(@_,0,shift);
752 return 0 unless @a == @b; # same len?
754 return 0 if pop(@a) ne pop(@b);
758 if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
761 .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
762 .Ip "split(/PATTERN/,EXPR)" 8 8
763 .Ip "split(/PATTERN/)" 8
765 Splits a string into an array of strings, and returns it.
766 (If not in an array context, returns the number of fields found and splits
768 (In an array context, you can force the split into @_
769 by using ?? as the pattern delimiters, but it still returns the array value.))
770 If EXPR is omitted, splits the $_ string.
771 If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
772 Anything matching PATTERN is taken to be a delimiter separating the fields.
773 (Note that the delimiter may be longer than one character.)
774 If LIMIT is specified, splits into no more than that many fields (though it
775 may split into fewer).
776 If LIMIT is unspecified, trailing null fields are stripped (which
777 potential users of pop() would do well to remember).
778 A pattern matching the null string (not to be confused with a null pattern,
779 which is one member of the set of patterns matching a null string)
780 will split the value of EXPR into separate characters at each point it
785 print join(\':\', split(/ */, \'hi there\'));
788 produces the output \*(L'h:i:t:h:e:r:e\*(R'.
790 The LIMIT parameter can be used to partially split a line
793 ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
796 (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
797 larger than the number of variables in the list, to avoid unnecessary work.
798 For the list above LIMIT would have been 4 by default.
799 In time critical applications it behooves you not to split into
800 more fields than you really need.)
802 If the PATTERN contains parentheses, additional array elements are created
803 from each matching substring in the delimiter.
805 split(/([,-])/,"1-10,20");
807 produces the array value
811 The pattern /PATTERN/ may be replaced with an expression to specify patterns
812 that vary at runtime.
813 (To do runtime compilation only once, use /$variable/o.)
814 As a special case, specifying a space (\'\ \') will split on white space
815 just as split with no arguments does, but leading white space does NOT
816 produce a null first field.
817 Thus, split(\'\ \') can be used to emulate
819 default behavior, whereas
820 split(/\ /) will give you as many null initial fields as there are
827 open(passwd, \'/etc/passwd\');
830 ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
833 ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
834 = split(\|/\|:\|/\|);
840 (Note that $shell above will still have a newline on it. See chop().)
843 .Ip "sprintf(FORMAT,LIST)" 8 4
844 Returns a string formatted by the usual printf conventions.
845 The * character is not supported.
848 Return the square root of EXPR.
849 If EXPR is omitted, returns square root of $_.
850 .Ip "srand(EXPR)" 8 4
852 Sets the random number seed for the
855 If EXPR is omitted, does srand(time).
856 .Ip "stat(FILEHANDLE)" 8 8
857 .Ip "stat FILEHANDLE" 8
859 .Ip "stat SCALARVARIABLE" 8
860 Returns a 13-element array giving the statistics for a file, either the file
861 opened via FILEHANDLE, or named by EXPR.
862 Typically used as follows:
866 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
867 $atime,$mtime,$ctime,$blksize,$blocks)
871 If stat is passed the special filehandle consisting of an underline,
872 no stat is done, but the current contents of the stat structure from
873 the last stat or filetest are returned.
878 if (-x $file && (($d) = stat(_)) && $d < 0) {
879 print "$file is executable NFS file\en";
883 .Ip "study(SCALAR)" 8 6
886 Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
887 doing many pattern matches on the string before it is next modified.
888 This may or may not save time, depending on the nature and number of patterns
889 you are searching on, and on the distribution of character frequencies in
890 the string to be searched\*(--you probably want to compare runtimes with and
891 without it to see which runs faster.
892 Those loops which scan for many short constant strings (including the constant
893 parts of more complex patterns) will benefit most.
894 You may have only one study active at a time\*(--if you study a different
895 scalar the first is \*(L"unstudied\*(R".
896 (The way study works is this: a linked list of every character in the string
897 to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
899 From each search string, the rarest character is selected, based on some
900 static frequency tables constructed from some C programs and English text.
901 Only those places that contain this \*(L"rarest\*(R" character are examined.)
903 For example, here is a loop which inserts index producing entries before any line
904 containing a certain pattern:
910 print ".IX foo\en" if /\ebfoo\eb/;
911 print ".IX bar\en" if /\ebbar\eb/;
912 print ".IX blurfl\en" if /\ebblurfl\eb/;
918 In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
919 will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
920 In general, this is a big win except in pathological cases.
921 The only question is whether it saves you more time than it took to build
922 the linked list in the first place.
924 Note that if you have to look for strings that you don't know till runtime,
925 you can build an entire loop as a string and eval that to avoid recompiling
926 all your patterns all the time.
927 Together with setting $/ to input entire files as one record, this can
928 be very fast, often faster than specialized programs like fgrep.
929 The following scans a list of files (@files)
930 for a list of words (@words), and prints out the names of those files that
935 $search = \'while (<>) { study;\';
936 foreach $word (@words) {
937 $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
941 $/ = "\e177"; # something that doesn't occur
942 eval $search; # this screams
943 $/ = "\en"; # put back to normal input delim
944 foreach $file (sort keys(%seen)) {
949 .Ip "substr(EXPR,OFFSET,LEN)" 8 2
950 Extracts a substring out of EXPR and returns it.
951 First character is at offset 0, or whatever you've set $[ to.
952 If OFFSET is negative, starts that far from the end of the string.
953 You can use the substr() function as an lvalue, in which case EXPR must
955 If you assign something shorter than LEN, the string will shrink, and
956 if you assign something longer than LEN, the string will grow to accommodate it.
957 To keep the string the same length you may need to pad or chop your value using
959 .Ip "syscall(LIST)" 8 6
961 Calls the system call specified as the first element of the list, passing
962 the remaining elements as arguments to the system call.
963 If unimplemented, produces a fatal error.
964 The arguments are interpreted as follows: if a given argument is numeric,
965 the argument is passed as an int.
966 If not, the pointer to the string value is passed.
967 You are responsible to make sure a string is pre-extended long enough
968 to receive any result that might be written into a string.
969 If your integer arguments are not literals and have never been interpreted
970 in a numeric context, you may need to add 0 to them to force them to look
974 do 'syscall.h'; # may need to run makelib
975 syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
978 .Ip "system(LIST)" 8 6
980 Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
981 is done first, and the parent process waits for the child process to complete.
982 Note that argument processing varies depending on the number of arguments.
983 The return value is the exit status of the program as returned by the wait()
985 To get the actual exit value divide by 256.
988 .Ip "symlink(OLDFILE,NEWFILE)" 8 2
989 Creates a new filename symbolically linked to the old filename.
990 Returns 1 for success, 0 otherwise.
991 On systems that don't support symbolic links, produces a fatal error at
993 To check for that, use eval:
996 $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
999 .Ip "tell(FILEHANDLE)" 8 6
1000 .Ip "tell FILEHANDLE" 8 6
1002 Returns the current file position for FILEHANDLE.
1003 FILEHANDLE may be an expression whose value gives the name of the actual
1005 If FILEHANDLE is omitted, assumes the file last read.
1006 .Ip "telldir(DIRHANDLE)" 8 5
1007 .Ip "telldir DIRHANDLE" 8
1008 Returns the current position of the readdir() routines on DIRHANDLE.
1009 Value may be given to seekdir() to access a particular location in
1011 Has the same caveats about possible directory compaction as the corresponding
1012 system library routine.
1014 Returns the number of non-leap seconds since January 1, 1970, UTC.
1015 Suitable for feeding to gmtime() and localtime().
1017 Returns a four-element array giving the user and system times, in seconds, for this
1018 process and the children of this process.
1020 ($user,$system,$cuser,$csystem) = times;
1022 .Ip "tr/SEARCHLIST/REPLACEMENTLIST/" 8 5
1023 .Ip "y/SEARCHLIST/REPLACEMENTLIST/" 8
1024 Translates all occurrences of the characters found in the search list with
1025 the corresponding character in the replacement list.
1026 It returns the number of characters replaced.
1027 If no string is specified via the =~ or !~ operator,
1028 the $_ string is translated.
1029 (The string specified with =~ must be a scalar variable, an array element,
1030 or an assignment to one of those, i.e. an lvalue.)
1035 is provided as a synonym for
1040 $ARGV[1] \|=~ \|y/A\-Z/a\-z/; \h'|3i'# canonicalize to lower case
1042 $cnt = tr/*/*/; \h'|3i'# count the stars in $_
1044 ($HOST = $host) =~ tr/a\-z/A\-Z/;
1046 y/\e001\-@[\-_{\-\e177/ /; \h'|3i'# change non-alphas to space
1049 .Ip "umask(EXPR)" 8 4
1052 Sets the umask for the process and returns the old one.
1053 If EXPR is omitted, merely returns current umask.
1054 .Ip "undef(EXPR)" 8 6
1057 Undefines the value of EXPR, which must be an lvalue.
1058 Use only on a scalar value, an entire array, or a subroutine name (using &).
1059 (Undef will probably not do what you expect on most predefined variables or
1061 Always returns the undefined value.
1062 You can omit the EXPR, in which case nothing is undefined, but you still
1063 get an undefined value that you could, for instance, return from a subroutine.
1069 undef $bar{'blurfl'};
1073 return (wantarray ? () : undef) if $they_blew_it;
1076 .Ip "unlink(LIST)" 8 4
1078 Deletes a list of files.
1079 Returns the number of files successfully deleted.
1083 $cnt = unlink \'a\', \'b\', \'c\';
1088 Note: unlink will not delete directories unless you are superuser and the
1092 Even if these conditions are met, be warned that unlinking a directory
1093 can inflict damage on your filesystem.
1095 .Ip "unpack(TEMPLATE,EXPR)" 8 4
1096 Unpack does the reverse of pack: it takes a string representing
1097 a structure and expands it out into an array value, returning the array
1099 The TEMPLATE has the same format as in the pack function.
1100 Here's a subroutine that does substring:
1105 local($what,$where,$howmuch) = @_;
1106 unpack("x$where a$howmuch", $what);
1112 sub ord { unpack("c",$_[0]); }
1115 .Ip "unshift(ARRAY,LIST)" 8 4
1116 Does the opposite of a
1118 Or the opposite of a
1120 depending on how you look at it.
1121 Prepends list to the front of the array, and returns the number of elements
1125 unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
1128 .Ip "utime(LIST)" 8 2
1129 .Ip "utime LIST" 8 2
1130 Changes the access and modification times on each file of a list of files.
1131 The first two elements of the list must be the NUMERICAL access and
1132 modification times, in that order.
1133 Returns the number of files successfully changed.
1134 The inode modification time of each file is set to the current time.
1135 Example of a \*(L"touch\*(R" command:
1141 utime $now, $now, @ARGV;
1144 .Ip "values(ASSOC_ARRAY)" 8 6
1145 .Ip "values ASSOC_ARRAY" 8
1146 Returns a normal array consisting of all the values of the named associative
1148 The values are returned in an apparently random order, but it is the same order
1149 as either the keys() or each() function would produce on the same array.
1150 See also keys() and each().
1151 .Ip "vec(EXPR,OFFSET,BITS)" 8 2
1152 Treats a string as a vector of unsigned integers, and returns the value
1153 of the bitfield specified.
1154 May also be assigned to.
1155 BITS must be a power of two from 1 to 32.
1157 Vectors created with vec() can also be manipulated with the logical operators
1159 which will assume a bit vector operation is desired when both operands are
1161 This interpretation is not enabled unless there is at least one vec() in
1162 your program, to protect older programs.
1164 Waits for a child process to terminate and returns the pid of the deceased
1165 process, or -1 if there are no child processes.
1166 The status is returned in $?.
1167 If you expected a child and didn't find it, you probably had a call to
1168 system, a close on a pipe, or backticks between the fork and the wait.
1169 These constructs also do a wait and may have harvested your child process.
1171 Returns true if the context of the currently executing subroutine
1172 is looking for an array value.
1173 Returns false if the context is looking for a scalar.
1176 return wantarray ? () : undef;
1179 .Ip "warn(LIST)" 8 4
1181 Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
1182 .Ip "write(FILEHANDLE)" 8 6
1185 Writes a formatted record (possibly multi-line) to the specified file,
1186 using the format associated with that file.
1187 By default the format for a file is the one having the same name is the
1188 filehandle, but the format for the current output channel (see
1190 may be set explicitly
1191 by assigning the name of the format to the $~ variable.
1193 Top of form processing is handled automatically:
1194 if there is insufficient room on the current page for the formatted
1195 record, the page is advanced by writing a form feed,
1196 a special top-of-page format is used
1197 to format the new page header, and then the record is written.
1198 By default the top-of-page format is \*(L"top\*(R", but it
1200 format of your choice by assigning the name to the $^ variable.
1201 The number of lines remaining on the current page is in variable $-, which
1202 can be set to 0 to force a new page.
1204 If FILEHANDLE is unspecified, output goes to the current default output channel,
1207 but may be changed by the
1210 If the FILEHANDLE is an EXPR, then the expression is evaluated and the
1211 resulting string is used to look up the name of the FILEHANDLE at run time.
1212 For more on formats, see the section on formats later on.
1214 Note that write is NOT the opposite of read.