2 ''' $RCSfile: perl.man,v $$Revision: 4.0.1.5 $$Date: 91/11/11 16:42:00 $
5 ''' Revision 4.0.1.5 91/11/11 16:42:00 lwall
6 ''' patch19: added little-endian pack/unpack options
8 ''' Revision 4.0.1.4 91/11/05 18:11:05 lwall
9 ''' patch11: added sort {} LIST
10 ''' patch11: added eval {}
11 ''' patch11: documented meaning of scalar(%foo)
12 ''' patch11: sprintf() now supports any length of s field
14 ''' Revision 4.0.1.3 91/06/10 01:26:02 lwall
15 ''' patch10: documented some newer features in addenda
17 ''' Revision 4.0.1.2 91/06/07 11:41:23 lwall
18 ''' patch4: added global modifier for pattern matches
19 ''' patch4: default top-of-form format is now FILEHANDLE_TOP
20 ''' patch4: added $^P variable to control calling of perldb routines
21 ''' patch4: added $^F variable to specify maximum system fd, default 2
22 ''' patch4: changed old $^P to $^X
24 ''' Revision 4.0.1.1 91/04/11 17:50:44 lwall
25 ''' patch1: fixed some typos
27 ''' Revision 4.0 91/03/20 01:38:08 lwall
44 .ie \\n(.$>=3 .ne \\$3
49 ''' Set up \*(-- to give an unbreakable dash;
50 ''' string Tr holds user defined translation string.
51 ''' Bell System Logo is used as a dummy character.
56 .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
57 .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
74 perl \- Practical Extraction and Report Language
77 [options] filename args
80 is an interpreted language optimized for scanning arbitrary text files,
81 extracting information from those text files, and printing reports based
83 It's also a good language for many system management tasks.
84 The language is intended to be practical (easy to use, efficient, complete)
85 rather than beautiful (tiny, elegant, minimal).
86 It combines (in the author's opinion, anyway) some of the best features of C,
87 \fIsed\fR, \fIawk\fR, and \fIsh\fR,
88 so people familiar with those languages should have little difficulty with it.
89 (Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
91 Expression syntax corresponds quite closely to C expression syntax.
92 Unlike most Unix utilities,
94 does not arbitrarily limit the size of your data\*(--if you've got
97 can slurp in your whole file as a single string.
98 Recursion is of unlimited depth.
99 And the hash tables used by associative arrays grow as necessary to prevent
100 degraded performance.
102 uses sophisticated pattern matching techniques to scan large amounts of
104 Although optimized for scanning text,
106 can also deal with binary data, and can make dbm files look like associative
107 arrays (where dbm is available).
110 scripts are safer than C programs
111 through a dataflow tracing mechanism which prevents many stupid security holes.
112 If you have a problem that would ordinarily use \fIsed\fR
113 or \fIawk\fR or \fIsh\fR, but it
114 exceeds their capabilities or must run a little faster,
115 and you don't want to write the silly thing in C, then
118 There are also translators to turn your
129 looks for your script in one of the following places:
131 Specified line by line via
133 switches on the command line.
135 Contained in the file specified by the first filename on the command line.
136 (Note that systems supporting the #! notation invoke interpreters this way.)
138 Passed in implicitly via standard input.
139 This only works if there are no filename arguments\*(--to pass
142 script you must explicitly specify a \- for the script name.
144 After locating your script,
146 compiles it to an internal form.
147 If the script is syntactically correct, it is executed.
149 Note: on first reading this section may not make much sense to you. It's here
150 at the front for easy reference.
152 A single-character option may be combined with the following option, if any.
153 This is particularly useful when invoking a script using the #! construct which
154 only allows one argument. Example:
158 #!/usr/bin/perl \-spi.bak # same as \-s \-p \-i.bak
165 specifies the record separator ($/) as an octal number.
166 If there are no digits, the null character is the separator.
167 Other switches may precede or follow the digits.
168 For example, if you have a version of
170 which can print filenames terminated by the null character, you can say this:
173 find . \-name '*.bak' \-print0 | perl \-n0e unlink
176 The special value 00 will cause Perl to slurp files in paragraph mode.
177 The value 0777 will cause Perl to slurp files whole since there is no
178 legal character with that value.
181 turns on autosplit mode when used with a
185 An implicit split command to the @F array
186 is done as the first thing inside the implicit while loop produced by
193 perl \-ane \'print pop(@F), "\en";\'
199 print pop(@F), "\en";
207 to check the syntax of the script and then exit without executing it.
210 runs the script under the perl debugger.
211 See the section on Debugging.
214 sets debugging flags.
215 To watch how it executes your script, use
217 (This only works if debugging is compiled into your
219 Another nice value is \-D1024, which lists your compiled syntax tree.
220 And \-D512 displays compiled regular expressions.
222 .BI \-e " commandline"
223 may be used to enter one line of script.
226 commands may be given to build up a multi-line script.
231 will not look for a script filename in the argument list.
234 specifies that files processed by the <> construct are to be edited
236 It does this by renaming the input file, opening the output file by the
237 same name, and selecting that output file as the default for print statements.
238 The extension, if supplied, is added to the name of the
239 old file to make a backup copy.
240 If no extension is supplied, no backup is made.
241 Saying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
246 #!/usr/bin/perl \-pi.bak
249 which is equivalent to
254 if ($ARGV ne $oldargv) {
255 rename($ARGV, $ARGV . \'.bak\');
256 open(ARGVOUT, ">$ARGV");
263 print; # this prints to original filename
270 form doesn't need to compare $ARGV to $oldargv to know when
271 the filename has changed.
272 It does, however, use ARGVOUT for the selected filehandle.
275 is restored as the default output filehandle after the loop.
277 You can use eof to locate the end of each input file, in case you want
278 to append to each file, or reset line numbering (see example under eof).
281 may be used in conjunction with
283 to tell the C preprocessor where to look for include files.
284 By default /usr/include and /usr/lib/perl are searched.
287 enables automatic line-ending processing. It has two effects:
288 first, it automatically chops the line terminator when used with
292 and second, it assigns $\e to have the value of
294 so that any print statements will have that line terminator added back on. If
296 is omitted, sets $\e to the current value of $/.
297 For instance, to trim lines to 80 columns:
300 perl -lpe \'substr($_, 80) = ""\'
303 Note that the assignment $\e = $/ is done when the switch is processed,
304 so the input record separator can be different than the output record
307 switch is followed by a
312 gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
315 This sets $\e to newline and then sets $/ to the null character.
320 to assume the following loop around your script, which makes it iterate
321 over filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
326 .\|.\|. # your script goes here
330 Note that the lines are not printed by default.
333 to have lines printed.
334 Here is an efficient way to delete all files older than a week:
337 find . \-mtime +7 \-print | perl \-nle \'unlink;\'
340 This is faster than using the \-exec switch of find because you don't have to
341 start a process on every filename found.
346 to assume the following loop around your script, which makes it iterate
347 over filename arguments somewhat like \fIsed\fR:
352 .\|.\|. # your script goes here
358 Note that the lines are printed automatically.
359 To suppress printing use the
369 causes your script to be run through the C preprocessor before
372 (Since both comments and cpp directives begin with the # character,
373 you should avoid starting comments with any words recognized
374 by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
377 enables some rudimentary switch parsing for switches on the command line
378 after the script name but before any filename arguments (or before a \-\|\-).
379 Any switch found there is removed from @ARGV and sets the corresponding variable in the
382 The following script prints \*(L"true\*(R" if and only if the script is
383 invoked with a \-xyz switch.
388 if ($xyz) { print "true\en"; }
395 use the PATH environment variable to search for the script
396 (unless the name of the script starts with a slash).
397 Typically this is used to emulate #! startup on machines that don't
398 support #!, in the following manner:
402 eval "exec /usr/bin/perl \-S $0 $*"
403 if $running_under_some_shell;
406 The system ignores the first line and feeds the script to /bin/sh,
407 which proceeds to try to execute the
409 script as a shell script.
410 The shell executes the second line as a normal shell command, and thus
414 On some systems $0 doesn't always contain the full pathname,
419 to search for the script if necessary.
422 locates the script, it parses the lines and ignores them because
423 the variable $running_under_some_shell is never true.
424 A better construct than $* would be ${1+"$@"}, which handles embedded spaces
425 and such in the filenames, but doesn't work if the script is being interpreted
427 In order to start up sh rather than csh, some systems may have to replace the
428 #! line with a line containing just
429 a colon, which will be politely ignored by perl.
430 Other systems can't control that, and need a totally devious construct that
431 will work under any of csh, sh or perl, such as the following:
435 eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
436 & eval 'exec /usr/bin/perl -S $0 $argv:q'
444 to dump core after compiling your script.
445 You can then take this core dump and turn it into an executable file
446 by using the undump program (not supplied).
447 This speeds startup at the expense of some disk space (which you can
448 minimize by stripping the executable).
449 (Still, a "hello world" executable comes out to about 200K on my machine.)
450 If you are going to run your executable as a set-id program then you
451 should probably compile it using taintperl rather than normal perl.
452 If you want to execute a portion of your script before dumping, use the
453 dump operator instead.
454 Note: availability of undump is platform specific and may not be available
455 for a specific port of perl.
460 to do unsafe operations.
461 Currently the only \*(L"unsafe\*(R" operations are the unlinking of directories while
462 running as superuser, and running setuid programs with fatal taint checks
463 turned into warnings.
466 prints the version and patchlevel of your
471 prints warnings about identifiers that are mentioned only once, and scalar
472 variables that are used before being set.
473 Also warns about redefined subroutines, and references to undefined
474 filehandles or filehandles opened readonly that you are attempting to
476 Also warns you if you use == on values that don't look like numbers, and if
477 your subroutines recurse more than 100 deep.
482 that the script is embedded in a message.
483 Leading garbage will be discarded until the first line that starts
484 with #! and contains the string "perl".
485 Any meaningful switches on that line will be applied (but only one
486 group of switches, as with normal #! processing).
487 If a directory name is specified, Perl will switch to that directory
488 before running the script.
491 switch only controls the the disposal of leading garbage.
492 The script must be terminated with _\|_END_\|_ if there is trailing garbage
493 to be ignored (the script can process any or all of the trailing garbage
494 via the DATA filehandle if desired).
495 .Sh "Data Types and Objects"
498 has three data types: scalars, arrays of scalars, and
499 associative arrays of scalars.
500 Normal arrays are indexed by number, and associative arrays by string.
502 The interpretation of operations and values in perl sometimes
503 depends on the requirements
504 of the context around the operation or value.
505 There are three major contexts: string, numeric and array.
506 Certain operations return array values
507 in contexts wanting an array, and scalar values otherwise.
508 (If this is true of an operation it will be mentioned in the documentation
510 Operations which return scalars don't care whether the context is looking
511 for a string or a number, but
512 scalar variables and values are interpreted as strings or numbers
513 as appropriate to the context.
514 A scalar is interpreted as TRUE in the boolean sense if it is not the null
516 Booleans returned by operators are 1 for true and 0 or \'\' (the null
519 There are actually two varieties of null string: defined and undefined.
520 Undefined null strings are returned when there is no real value for something,
521 such as when there was an error, or at end of file, or when you refer
522 to an uninitialized variable or element of an array.
523 An undefined null string may become defined the first time you access it, but
524 prior to that you can use the defined() operator to determine whether the
525 value is defined or not.
527 References to scalar variables always begin with \*(L'$\*(R', even when referring
528 to a scalar that is part of an array.
533 $days \h'|2i'# a simple scalar variable
534 $days[28] \h'|2i'# 29th element of array @days
535 $days{\'Feb\'}\h'|2i'# one value from an associative array
536 $#days \h'|2i'# last index of array @days
538 but entire arrays or array slices are denoted by \*(L'@\*(R':
540 @days \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
541 @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
542 @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
544 and entire associative arrays are denoted by \*(L'%\*(R':
546 %days \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
549 Any of these eight constructs may serve as an lvalue,
550 that is, may be assigned to.
551 (It also turns out that an assignment is itself an lvalue in
552 certain contexts\*(--see examples under s, tr and chop.)
553 Assignment to a scalar evaluates the righthand side in a scalar context,
554 while assignment to an array or array slice evaluates the righthand side
557 You may find the length of array @days by evaluating
558 \*(L"$#days\*(R", as in
560 (Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
561 Assigning to $#days changes the length of the array.
562 Shortening an array by this method does not actually destroy any values.
563 Lengthening an array that was previously shortened recovers the values that
564 were in those elements.
565 You can also gain some measure of efficiency by preextending an array that
567 (You can also extend an array by assigning to an element that is off the
569 This differs from assigning to $#whatever in that intervening values
570 are set to null rather than recovered.)
571 You can truncate an array down to nothing by assigning the null list () to
573 The following are exactly equivalent
577 $#whatever = $[ \- 1;
581 If you evaluate an array in a scalar context, it returns the length of
583 The following is always true:
586 scalar(@whatever) == $#whatever \- $[ + 1;
589 If you evaluate an associative array in a scalar context, it returns
590 a value which is true if and only if the array contains any elements.
591 (If there are any elements, the value returned is a string consisting
592 of the number of used buckets and the number of allocated buckets, separated
595 Multi-dimensional arrays are not directly supported, but see the discussion
596 of the $; variable later for a means of emulating multiple subscripts with
597 an associative array.
598 You could also write a subroutine to turn multiple subscripts into a single
601 Every data type has its own namespace.
602 You can, without fear of conflict, use the same name for a scalar variable,
603 an array, an associative array, a filehandle, a subroutine name, and/or
605 Since variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
606 or \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
607 with respect to variable names.
608 (They ARE reserved with respect to labels and filehandles, however, which
609 don't have an initial special character.
610 Hint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
611 Using uppercase filehandles also improves readability and protects you
612 from conflict with future reserved words.)
613 Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
615 Names which start with a letter may also contain digits and underscores.
616 Names which do not start with a letter are limited to one character,
617 e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
618 (Most of the one character names have a predefined significance to
622 Numeric literals are specified in any of the usual floating point or
634 String literals are delimited by either single or double quotes.
635 They work much like shell quotes:
636 double-quoted string literals are subject to backslash and variable
637 substitution; single-quoted strings are not (except for \e\' and \e\e).
638 The usual backslash rules apply for making characters such as newline, tab,
639 etc., as well as some more exotic forms:
652 \el lowercase next char
653 \eu uppercase next char
654 \eL lowercase till \eE
655 \eU uppercase till \eE
656 \eE end case modification
659 You can also embed newlines directly in your strings, i.e. they can end on
660 a different line than they begin.
661 This is nice, but if you forget your trailing quote, the error will not be
664 finds another line containing the quote character, which
665 may be much further on in the script.
666 Variable substitution inside strings is limited to scalar variables, normal
667 array values, and array slices.
668 (In other words, identifiers beginning with $ or @, followed by an optional
669 bracketed expression as a subscript.)
670 The following code segment prints out \*(L"The price is $100.\*(R"
674 $Price = \'$100\';\h'|3.5i'# not interpreted
675 print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
678 Note that you can put curly brackets around the identifier to delimit it
679 from following alphanumerics.
680 Also note that a single quoted string must be separated from a preceding
681 word by a space, since single quote is a valid character in an identifier
684 Two special literals are _\|_LINE_\|_ and _\|_FILE_\|_, which represent the current
685 line number and filename at that point in your program.
686 They may only be used as separate tokens; they will not be interpolated
688 In addition, the token _\|_END_\|_ may be used to indicate the logical end of the
689 script before the actual end of file.
690 Any following text is ignored (but may be read via the DATA filehandle).
691 The two control characters ^D and ^Z are synonyms for _\|_END_\|_.
693 A word that doesn't have any other interpretation in the grammar will be
694 treated as if it had single quotes around it.
695 For this purpose, a word consists only of alphanumeric characters and underline,
696 and must start with an alphabetic character.
697 As with filehandles and labels, a bare word that consists entirely of
698 lowercase letters risks conflict with future reserved words, and if you
701 switch, Perl will warn you about any such words.
703 Array values are interpolated into double-quoted strings by joining all the
704 elements of the array with the delimiter specified in the $" variable,
706 (Since in versions of perl prior to 3.0 the @ character was not a metacharacter
707 in double-quoted strings, the interpolation of @array, $array[EXPR],
708 @array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
709 referenced elsewhere in the program or is predefined.)
710 The following are equivalent:
714 $temp = join($",@ARGV);
720 Within search patterns (which also undergo double-quotish substitution)
721 there is a bad ambiguity: Is /$foo[bar]/ to be
722 interpreted as /${foo}[bar]/ (where [bar] is a character class for the
723 regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
725 If @foo doesn't otherwise exist, then it's obviously a character class.
726 If @foo exists, perl takes a good guess about [bar], and is almost always right.
727 If it does guess wrong, or if you're just plain paranoid,
728 you can force the correct interpretation with curly brackets as above.
730 A line-oriented form of quoting is based on the shell here-is syntax.
731 Following a << you specify a string to terminate the quoted material, and all lines
732 following the current line down to the terminating string are the value
734 The terminating string may be either an identifier (a word), or some
736 If quoted, the type of quotes you use determines the treatment of the text,
737 just as in regular quoting.
738 An unquoted identifier works like double quotes.
739 There must be no space between the << and the identifier.
740 (If you put a space it will be treated as a null identifier, which is
741 valid, and matches the first blank line\*(--see Merry Christmas example below.)
742 The terminating string must appear by itself (unquoted and with no surrounding
743 whitespace) on the terminating line.
746 print <<EOF; # same as above
750 print <<"EOF"; # same as above
754 print << x 10; # null identifier is delimiter
757 print <<`EOC`; # execute commands
762 print <<foo, <<bar; # you can stack them
769 Array literals are denoted by separating individual values by commas, and
770 enclosing the list in parentheses:
776 In a context not requiring an array value, the value of the array literal
777 is the value of the final element, as in the C comma operator.
782 @foo = (\'cc\', \'\-E\', $bar);
784 assigns the entire array value to array foo, but
786 $foo = (\'cc\', \'\-E\', $bar);
789 assigns the value of variable bar to variable foo.
790 Note that the value of an actual array in a scalar context is the length
791 of the array; the following assigns to $foo the value 3:
795 @foo = (\'cc\', \'\-E\', $bar);
796 $foo = @foo; # $foo gets 3
799 You may have an optional comma before the closing parenthesis of an
800 array literal, so that you can say:
810 When a LIST is evaluated, each element of the list is evaluated in
811 an array context, and the resulting array value is interpolated into LIST
812 just as if each individual element were a member of LIST. Thus arrays
813 lose their identity in a LIST\*(--the list
817 contains all the elements of @foo followed by all the elements of @bar,
818 followed by all the elements returned by the subroutine named SomeSub.
820 A list value may also be subscripted like a normal array.
824 $time = (stat($file))[8]; # stat returns array value
825 $digit = ('a','b','c','d','e','f')[$digit-10];
826 return (pop(@foo),pop(@foo))[0];
830 Array lists may be assigned to if and only if each element of the list
834 ($a, $b, $c) = (1, 2, 3);
836 ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
838 The final element may be an array or an associative array:
840 ($a, $b, @rest) = split;
841 local($a, $b, %rest) = @_;
844 You can actually put an array anywhere in the list, but the first array
845 in the list will soak up all the values, and anything after it will get
847 This may be useful in a local().
849 An associative array literal contains pairs of values to be interpreted
850 as a key and a value:
854 # same as map assignment above
855 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
858 Array assignment in a scalar context returns the number of elements
859 produced by the expression on the right side of the assignment:
862 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
866 There are several other pseudo-literals that you should know about.
867 If a string is enclosed by backticks (grave accents), it first undergoes
868 variable substitution just like a double quoted string.
869 It is then interpreted as a command, and the output of that command
870 is the value of the pseudo-literal, like in a shell.
871 In a scalar context, a single string consisting of all the output is
873 In an array context, an array of values is returned, one for each line
875 (You can set $/ to use a different line terminator.)
876 The command is executed each time the pseudo-literal is evaluated.
877 The status value of the command is returned in $? (see Predefined Names
878 for the interpretation of $?).
879 Unlike in \f2csh\f1, no translation is done on the return
880 data\*(--newlines remain newlines.
881 Unlike in any of the shells, single quotes do not hide variable names
882 in the command from interpretation.
883 To pass a $ through to the shell you need to hide it with a backslash.
885 Evaluating a filehandle in angle brackets yields the next line
886 from that file (newline included, so it's never false until EOF, at
887 which time an undefined value is returned).
888 Ordinarily you must assign that value to a variable,
889 but there is one situation where an automatic assignment happens.
890 If (and only if) the input symbol is the only thing inside the conditional of a
893 automatically assigned to the variable \*(L"$_\*(R".
894 (This may seem like an odd thing to you, but you'll use the construct
898 Anyway, the following lines are equivalent to each other:
902 while ($_ = <STDIN>) { print; }
903 while (<STDIN>) { print; }
904 for (\|;\|<STDIN>;\|) { print; }
905 print while $_ = <STDIN>;
920 will also work except in packages, where they would be interpreted as
921 local identifiers rather than global.)
922 Additional filehandles may be created with the
926 If a <FILEHANDLE> is used in a context that is looking for an array, an array
927 consisting of all the input lines is returned, one line per array element.
928 It's easy to make a LARGE data space this way, so use with care.
930 The null filehandle <> is special and can be used to emulate the behavior of
931 \fIsed\fR and \fIawk\fR.
932 Input from <> comes either from standard input, or from each file listed on
934 Here's how it works: the first time <> is evaluated, the ARGV array is checked,
935 and if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
937 The ARGV array is then processed as a list of filenames.
943 .\|.\|. # code for each line
949 unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
950 while ($ARGV = shift) {
953 .\|.\|. # code for each line
958 except that it isn't as cumbersome to say.
959 It really does shift array ARGV and put the current filename into
961 It also uses filehandle ARGV internally.
962 You can modify @ARGV before the first <> as long as you leave the first
963 filename at the beginning of the array.
964 Line numbers ($.) continue as if the input was one big happy file.
965 (But see example under eof for how to reset line numbers on each file.)
968 If you want to set @ARGV to your own list of files, go right ahead.
969 If you want to pass switches into your script, you can
970 put a loop on the front like this:
974 while ($_ = $ARGV[0], /\|^\-/\|) {
976 last if /\|^\-\|\-$\|/\|;
977 /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
978 /\|^\-v\|/ \|&& \|$verbose++;
979 .\|.\|. # other switches
982 .\|.\|. # code for each line
986 The <> symbol will return FALSE only once.
987 If you call it again after this it will assume you are processing another
988 @ARGV list, and if you haven't set @ARGV, will input from
991 If the string inside the angle brackets is a reference to a scalar variable
993 then that variable contains the name of the filehandle to input from.
995 If the string inside angle brackets is not a filehandle, it is interpreted
996 as a filename pattern to be globbed, and either an array of filenames or the
997 next filename in the list is returned, depending on context.
998 One level of $ interpretation is done first, but you can't say <$foo>
999 because that's an indirect filehandle as explained in the previous
1001 You could insert curly brackets to force interpretation as a
1002 filename glob: <${foo}>.
1014 open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
1021 In fact, it's currently implemented that way.
1022 (Which means it will not work on filenames with spaces in them unless
1023 you have /bin/csh on your machine.)
1024 Of course, the shortest way to do the above is:
1034 script consists of a sequence of declarations and commands.
1035 The only things that need to be declared in
1037 are report formats and subroutines.
1038 See the sections below for more information on those declarations.
1039 All uninitialized user-created objects are assumed to
1040 start with a null or 0 value until they
1041 are defined by some explicit operation such as assignment.
1042 The sequence of commands is executed just once, unlike in
1046 scripts, where the sequence of commands is executed for each input line.
1047 While this means that you must explicitly loop over the lines of your input file
1048 (or files), it also means you have much more control over which files and which
1050 (Actually, I'm lying\*(--it is possible to do an implicit loop with either the
1056 A declaration can be put anywhere a command can, but has no effect on the
1057 execution of the primary sequence of commands\*(--declarations all take effect
1059 Typically all the declarations are put at the beginning or the end of the script.
1062 is, for the most part, a free-form language.
1063 (The only exception to this is format declarations, for fairly obvious reasons.)
1064 Comments are indicated by the # character, and extend to the end of the line.
1065 If you attempt to use /* */ C comments, it will be interpreted either as
1066 division or pattern matching, depending on the context.
1068 .Sh "Compound statements"
1071 a sequence of commands may be treated as one command by enclosing it
1073 We will call this a BLOCK.
1075 The following compound commands may be used to control flow:
1080 if (EXPR) BLOCK else BLOCK
1081 if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
1082 LABEL while (EXPR) BLOCK
1083 LABEL while (EXPR) BLOCK continue BLOCK
1084 LABEL for (EXPR; EXPR; EXPR) BLOCK
1085 LABEL foreach VAR (ARRAY) BLOCK
1086 LABEL BLOCK continue BLOCK
1089 Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
1091 This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
1092 If you want to write conditionals without curly brackets there are several
1093 other ways to do it.
1094 The following all do the same thing:
1098 if (!open(foo)) { die "Can't open $foo: $!"; }
1099 die "Can't open $foo: $!" unless open(foo);
1100 open(foo) || die "Can't open $foo: $!"; # foo or bust!
1101 open(foo) ? \'hi mom\' : die "Can't open $foo: $!";
1102 # a bit exotic, that last one
1108 statement is straightforward.
1109 Since BLOCKs are always bounded by curly brackets, there is never any
1110 ambiguity about which
1119 the sense of the test is reversed.
1123 statement executes the block as long as the expression is true
1124 (does not evaluate to the null string or 0).
1125 The LABEL is optional, and if present, consists of an identifier followed by
1127 The LABEL identifies the loop for the loop control statements
1135 BLOCK, it is always executed just before
1136 the conditional is about to be evaluated again, similarly to the third part
1140 Thus it can be used to increment a loop variable, even when the loop has
1141 been continued via the
1143 statement (similar to the C \*(L"continue\*(R" statement).
1147 is replaced by the word
1149 the sense of the test is reversed, but the conditional is still tested before
1150 the first iteration.
1156 statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
1157 is true if the value of the last command in that block is true.
1161 loop works exactly like the corresponding
1167 for ($i = 1; $i < 10; $i++) {
1181 The foreach loop iterates over a normal array value and sets the variable
1182 VAR to be each element of the array in turn.
1183 The variable is implicitly local to the loop, and regains its former value
1184 upon exiting the loop.
1185 The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
1186 so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
1187 If VAR is omitted, $_ is set to each value.
1188 If ARRAY is an actual array (as opposed to an expression returning an array
1189 value), you can modify each element of the array
1190 by modifying VAR inside the loop.
1195 for (@ary) { s/foo/bar/; }
1197 foreach $elem (@elements) {
1202 for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
1203 print $_, "\en"; sleep(1);
1206 for (1..15) { print "Merry Christmas\en"; }
1209 foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'})) {
1210 print "Item: $item\en";
1215 The BLOCK by itself (labeled or not) is equivalent to a loop that executes
1217 Thus you can use any of the loop control statements in it to leave or
1222 This construct is particularly nice for doing case structures.
1227 if (/^abc/) { $abc = 1; last foo; }
1228 if (/^def/) { $def = 1; last foo; }
1229 if (/^xyz/) { $xyz = 1; last foo; }
1234 There is no official switch statement in perl, because there
1235 are already several ways to write the equivalent.
1236 In addition to the above, you could write
1241 $abc = 1, last foo if /^abc/;
1242 $def = 1, last foo if /^def/;
1243 $xyz = 1, last foo if /^xyz/;
1251 /^abc/ && do { $abc = 1; last foo; };
1252 /^def/ && do { $def = 1; last foo; };
1253 /^xyz/ && do { $xyz = 1; last foo; };
1261 /^abc/ && ($abc = 1, last foo);
1262 /^def/ && ($def = 1, last foo);
1263 /^xyz/ && ($xyz = 1, last foo);
1280 As it happens, these are all optimized internally to a switch structure,
1281 so perl jumps directly to the desired statement, and you needn't worry
1282 about perl executing a lot of unnecessary statements when you have a string
1283 of 50 elsifs, as long as you are testing the same simple scalar variable
1284 using ==, eq, or pattern matching as above.
1285 (If you're curious as to whether the optimizer has done this for a particular
1286 case statement, you can use the \-D1024 switch to list the syntax tree
1288 .Sh "Simple statements"
1289 The only kind of simple statement is an expression evaluated for its side
1291 Every expression (simple statement) must be terminated with a semicolon.
1292 Note that this is like C, but unlike Pascal (and
1295 Any simple statement may optionally be followed by a
1296 single modifier, just before the terminating semicolon.
1297 The possible modifiers are:
1311 modifiers have the expected semantics.
1316 modifiers also have the expected semantics (conditional evaluated first),
1317 except when applied to a do-BLOCK or a do-SUBROUTINE command,
1318 in which case the block executes once before the conditional is evaluated.
1319 This is so that you can write loops like:
1326 } until $_ \|eq \|".\|\e\|n";
1331 operator below. Note also that the loop control commands described later will
1332 NOT work in this construct, since modifiers don't take loop labels.
1337 expressions work almost exactly like C expressions, only the differences
1338 will be mentioned here.
1344 The exponentiation operator.
1346 The exponentiation assignment operator.
1348 The null list, used to initialize an array to null.
1350 Concatenation of two strings.
1352 The concatenation assignment operator.
1354 String equality (== is numeric equality).
1355 For a mnemonic just think of \*(L"eq\*(R" as a string.
1356 (If you are used to the
1358 behavior of using == for either string or numeric equality
1359 based on the current form of the comparands, beware!
1360 You must be explicit here.)
1362 String inequality (!= is numeric inequality).
1366 String greater than.
1368 String less than or equal.
1370 String greater than or equal.
1372 String comparison, returning -1, 0, or 1.
1374 Numeric comparison, returning -1, 0, or 1.
1376 Certain operations search or modify the string \*(L"$_\*(R" by default.
1377 This operator makes that kind of operation work on some other string.
1378 The right argument is a search pattern, substitution, or translation.
1379 The left argument is what is supposed to be searched, substituted, or
1380 translated instead of the default \*(L"$_\*(R".
1381 The return value indicates the success of the operation.
1382 (If the right argument is an expression other than a search pattern,
1383 substitution, or translation, it is interpreted as a search pattern
1385 This is less efficient than an explicit search, since the pattern must
1386 be compiled every time the expression is evaluated.)
1387 The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
1389 Just like =~ except the return value is negated.
1391 The repetition operator.
1392 Returns a string consisting of the left operand repeated the
1393 number of times specified by the right operand.
1394 In an array context, if the left operand is a list in parens, it repeats
1398 print \'\-\' x 80; # print row of dashes
1399 print \'\-\' x80; # illegal, x80 is identifier
1401 print "\et" x ($tab/8), \' \' x ($tab%8); # tab over
1403 @ones = (1) x 80; # an array of 80 1's
1404 @ones = (5) x @ones; # set all elements to 5
1408 The repetition assignment operator.
1409 Only works on scalars.
1411 The range operator, which is really two different operators depending
1413 In an array context, returns an array of values counting (by ones)
1414 from the left value to the right value.
1415 This is useful for writing \*(L"for (1..10)\*(R" loops and for doing
1416 slice operations on arrays.
1418 In a scalar context, .\|. returns a boolean value.
1419 The operator is bistable, like a flip-flop..
1420 Each .\|. operator maintains its own boolean state.
1421 It is false as long as its left operand is false.
1422 Once the left operand is true, the range operator stays true
1423 until the right operand is true,
1424 AFTER which the range operator becomes false again.
1425 (It doesn't become false till the next time the range operator is evaluated.
1426 It can become false on the same evaluation it became true, but it still returns
1428 The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
1429 and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
1430 The scalar .\|. operator is primarily intended for doing line number ranges
1432 the fashion of \fIsed\fR or \fIawk\fR.
1433 The precedence is a little lower than || and &&.
1434 The value returned is either the null string for false, or a sequence number
1435 (beginning with 1) for true.
1436 The sequence number is reset for each range encountered.
1437 The final sequence number in a range has the string \'E0\' appended to it, which
1438 doesn't affect its numeric value, but gives you something to search for if you
1439 want to exclude the endpoint.
1440 You can exclude the beginning point by waiting for the sequence number to be
1442 If either operand of scalar .\|. is static, that operand is implicitly compared
1443 to the $. variable, the current line number.
1448 As a scalar operator:
1449 if (101 .\|. 200) { print; } # print 2nd hundred lines
1451 next line if (1 .\|. /^$/); # skip header lines
1453 s/^/> / if (/^$/ .\|. eof()); # quote body
1456 As an array operator:
1457 for (101 .\|. 200) { print; } # print $_ 100 times
1459 @foo = @foo[$[ .\|. $#foo]; # an expensive no-op
1460 @foo = @foo[$#foo-4 .\|. $#foo]; # slice last 5 items
1465 This unary operator takes one argument, either a filename or a filehandle,
1466 and tests the associated file to see if something is true about it.
1467 If the argument is omitted, tests $_, except for \-t, which tests
1469 It returns 1 for true and \'\' for false, or the undefined value if the
1471 Precedence is higher than logical and relational operators, but lower than
1472 arithmetic operators.
1473 The operator may be any of:
1475 \-r File is readable by effective uid.
1476 \-w File is writable by effective uid.
1477 \-x File is executable by effective uid.
1478 \-o File is owned by effective uid.
1479 \-R File is readable by real uid.
1480 \-W File is writable by real uid.
1481 \-X File is executable by real uid.
1482 \-O File is owned by real uid.
1484 \-z File has zero size.
1485 \-s File has non-zero size (returns size).
1486 \-f File is a plain file.
1487 \-d File is a directory.
1488 \-l File is a symbolic link.
1489 \-p File is a named pipe (FIFO).
1490 \-S File is a socket.
1491 \-b File is a block special file.
1492 \-c File is a character special file.
1493 \-u File has setuid bit set.
1494 \-g File has setgid bit set.
1495 \-k File has sticky bit set.
1496 \-t Filehandle is opened to a tty.
1497 \-T File is a text file.
1498 \-B File is a binary file (opposite of \-T).
1499 \-M Age of file in days when script started.
1500 \-A Same for access time.
1501 \-C Same for inode change time.
1504 The interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
1505 is based solely on the mode of the file and the uids and gids of the user.
1506 There may be other reasons you can't actually read, write or execute the file.
1507 Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and
1508 \-x and \-X return 1 if any execute bit is set in the mode.
1509 Scripts run by the superuser may thus need to do a stat() in order to determine
1510 the actual mode of the file, or temporarily set the uid to something else.
1518 next unless \-f $_; # ignore specials
1523 Note that \-s/a/b/ does not do a negated substitution.
1524 Saying \-exp($foo) still works as expected, however\*(--only single letters
1525 following a minus are interpreted as file tests.
1527 The \-T and \-B switches work as follows.
1528 The first block or so of the file is examined for odd characters such as
1529 strange control codes or metacharacters.
1530 If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
1531 Also, any file containing null in the first block is considered a binary file.
1532 If \-T or \-B is used on a filehandle, the current stdio buffer is examined
1533 rather than the first block.
1534 Both \-T and \-B return TRUE on a null file, or a file at EOF when testing
1537 If any of the file tests (or either stat operator) are given the special
1538 filehandle consisting of a solitary underline, then the stat structure
1539 of the previous file test (or stat operator) is used, saving a system
1541 (This doesn't work with \-t, and you need to remember that lstat and -l
1542 will leave values in the stat structure for the symbolic link, not the
1547 print "Can do.\en" if -r $a || -w _ || -x _;
1551 print "Readable\en" if -r _;
1552 print "Writable\en" if -w _;
1553 print "Executable\en" if -x _;
1554 print "Setuid\en" if -u _;
1555 print "Setgid\en" if -g _;
1556 print "Sticky\en" if -k _;
1557 print "Text\en" if -T _;
1558 print "Binary\en" if -B _;
1562 Here is what C has that
1566 Address-of operator.
1568 Dereference-address operator.
1570 Type casting operator.
1574 does a certain amount of expression evaluation at compile time, whenever
1575 it determines that all of the arguments to an operator are static and have
1577 In particular, string concatenation happens at compile time between literals that don't do variable substitution.
1578 Backslash interpretation also happens at compile time.
1583 \'Now is the time for all\' . "\|\e\|n" .
1584 \'good men to come to.\'
1587 and this all reduces to one string internally.
1589 The autoincrement operator has a little extra built-in magic to it.
1590 If you increment a variable that is numeric, or that has ever been used in
1591 a numeric context, you get a normal increment.
1592 If, however, the variable has only been used in string contexts since it
1593 was set, and has a value that is not null and matches the
1594 pattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
1595 as a string, preserving each character within its range, with carry:
1598 print ++($foo = \'99\'); # prints \*(L'100\*(R'
1599 print ++($foo = \'a0\'); # prints \*(L'a1\*(R'
1600 print ++($foo = \'Az\'); # prints \*(L'Ba\*(R'
1601 print ++($foo = \'zz\'); # prints \*(L'aaa\*(R'
1604 The autodecrement is not magical.
1606 The range operator (in an array context) makes use of the magical
1607 autoincrement algorithm if the minimum and maximum are strings.
1610 @alphabet = (\'A\' .. \'Z\');
1612 to get all the letters of the alphabet, or
1614 $hexdigit = (0 .. 9, \'a\' .. \'f\')[$num & 15];
1616 to get a hexadecimal digit, or
1618 @z2 = (\'01\' .. \'31\'); print @z2[$mday];
1620 to get dates with leading zeros.
1621 (If the final value specified is not in the sequence that the magical increment
1622 would produce, the sequence goes until the next value would be longer than
1623 the final value specified.)
1625 The || and && operators differ from C's in that, rather than returning 0 or 1,
1626 they return the last value evaluated.
1627 Thus, a portable way to find out the home directory might be:
1630 $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
1631 (getpwuid($<))[7] || die "You're homeless!\en";
1635 Along with the literals and variables mentioned earlier,
1636 the operations in the following section can serve as terms in an expression.
1637 Some of these operations take a LIST as an argument.
1638 Such a list can consist of any combination of scalar arguments or array values;
1639 the array values will be included in the list as if each individual element were
1640 interpolated at that point in the list, forming a longer single-dimensional
1642 Elements of the LIST should be separated by commas.
1643 If an operation is listed both with and without parentheses around its
1644 arguments, it means you can either use it as a unary operator or
1646 To use it as a function call, the next token on the same line must
1647 be a left parenthesis.
1648 (There may be intervening white space.)
1649 Such a function then has highest precedence, as you would expect from
1651 If any token other than a left parenthesis follows, then it is a
1652 unary operator, with a precedence depending only on whether it is a LIST
1654 LIST operators have lowest precedence.
1655 All other unary operators have a precedence greater than relational operators
1656 but less than arithmetic operators.
1657 See the section on Precedence.
1661 This is just like the /pattern/ search, except that it matches only once between
1665 This is a useful optimization when you only want to see the first occurrence of
1666 something in each file of a set of files, for instance.
1667 Only ?? patterns local to the current package are reset.
1668 .Ip "accept(NEWSOCKET,GENERICSOCKET)" 8 2
1669 Does the same thing that the accept system call does.
1670 Returns true if it succeeded, false otherwise.
1671 See example in section on Interprocess Communication.
1672 .Ip "alarm(SECONDS)" 8 4
1673 .Ip "alarm SECONDS" 8
1674 Arranges to have a SIGALRM delivered to this process after the specified number
1675 of seconds (minus 1, actually) have elapsed. Thus, alarm(15) will cause
1676 a SIGALRM at some point more than 14 seconds in the future.
1677 Only one timer may be counting at once. Each call disables the previous
1678 timer, and an argument of 0 may be supplied to cancel the previous timer
1679 without starting a new one.
1680 The returned value is the amount of time remaining on the previous timer.
1681 .Ip "atan2(Y,X)" 8 2
1682 Returns the arctangent of Y/X in the range
1683 .if t \-\(*p to \(*p.
1685 .Ip "bind(SOCKET,NAME)" 8 2
1686 Does the same thing that the bind system call does.
1687 Returns true if it succeeded, false otherwise.
1688 NAME should be a packed address of the proper type for the socket.
1689 See example in section on Interprocess Communication.
1690 .Ip "binmode(FILEHANDLE)" 8 4
1691 .Ip "binmode FILEHANDLE" 8 4
1692 Arranges for the file to be read in \*(L"binary\*(R" mode in operating systems
1693 that distinguish between binary and text files.
1694 Files that are not read in binary mode have CR LF sequences translated
1695 to LF on input and LF translated to CR LF on output.
1696 Binmode has no effect under Unix.
1697 If FILEHANDLE is an expression, the value is taken as the name of
1701 Returns the context of the current subroutine call:
1704 ($package,$filename,$line) = caller;
1707 With EXPR, returns some extra information that the debugger uses to print
1708 a stack trace. The value of EXPR indicates how many call frames to go
1709 back before the current one.
1710 .Ip "chdir(EXPR)" 8 2
1711 .Ip "chdir EXPR" 8 2
1712 Changes the working directory to EXPR, if possible.
1713 If EXPR is omitted, changes to home directory.
1714 Returns 1 upon success, 0 otherwise.
1717 .Ip "chmod(LIST)" 8 2
1718 .Ip "chmod LIST" 8 2
1719 Changes the permissions of a list of files.
1720 The first element of the list must be the numerical mode.
1721 Returns the number of files successfully changed.
1725 $cnt = chmod 0755, \'foo\', \'bar\';
1726 chmod 0755, @executables;
1729 .Ip "chop(LIST)" 8 7
1730 .Ip "chop(VARIABLE)" 8
1731 .Ip "chop VARIABLE" 8
1733 Chops off the last character of a string and returns the character chopped.
1734 It's used primarily to remove the newline from the end of an input record,
1735 but is much more efficient than s/\en// because it neither scans nor copies
1737 If VARIABLE is omitted, chops $_.
1743 chop; # avoid \en on last field
1744 @array = split(/:/);
1749 You can actually chop anything that's an lvalue, including an assignment:
1752 chop($cwd = \`pwd\`);
1753 chop($answer = <STDIN>);
1756 If you chop a list, each element is chopped.
1757 Only the value of the last chop is returned.
1758 .Ip "chown(LIST)" 8 2
1759 .Ip "chown LIST" 8 2
1760 Changes the owner (and group) of a list of files.
1761 The first two elements of the list must be the NUMERICAL uid and gid,
1763 Returns the number of files successfully changed.
1767 $cnt = chown $uid, $gid, \'foo\', \'bar\';
1768 chown $uid, $gid, @filenames;
1772 Here's an example that looks up non-numeric uids in the passwd file:
1782 open(pass, \'/etc/passwd\') || die "Can't open passwd: $!\en";
1785 open(pass, \'/etc/passwd\')
1786 || die "Can't open passwd: $!\en";
1789 ($login,$pass,$uid,$gid) = split(/:/);
1790 $uid{$login} = $uid;
1791 $gid{$login} = $gid;
1793 @ary = <${pattern}>; # get filenames
1794 if ($uid{$user} eq \'\') {
1795 die "$user not in passwd file";
1798 chown $uid{$user}, $gid{$user}, @ary;
1802 .Ip "chroot(FILENAME)" 8 5
1803 .Ip "chroot FILENAME" 8
1804 Does the same as the system call of that name.
1805 If you don't know what it does, don't worry about it.
1806 If FILENAME is omitted, does chroot to $_.
1807 .Ip "close(FILEHANDLE)" 8 5
1808 .Ip "close FILEHANDLE" 8
1809 Closes the file or pipe associated with the file handle.
1810 You don't have to close FILEHANDLE if you are immediately going to
1811 do another open on it, since open will close it for you.
1814 However, an explicit close on an input file resets the line counter ($.), while
1815 the implicit close done by
1818 Also, closing a pipe will wait for the process executing on the pipe to complete,
1819 in case you want to look at the output of the pipe afterwards.
1820 Closing a pipe explicitly also puts the status value of the command into $?.
1825 open(OUTPUT, \'|sort >foo\'); # pipe to sort
1826 .\|.\|. # print stuff to output
1827 close OUTPUT; # wait for sort to finish
1828 open(INPUT, \'foo\'); # get sort's results
1831 FILEHANDLE may be an expression whose value gives the real filehandle name.
1832 .Ip "closedir(DIRHANDLE)" 8 5
1833 .Ip "closedir DIRHANDLE" 8
1834 Closes a directory opened by opendir().
1835 .Ip "connect(SOCKET,NAME)" 8 2
1836 Does the same thing that the connect system call does.
1837 Returns true if it succeeded, false otherwise.
1838 NAME should be a package address of the proper type for the socket.
1839 See example in section on Interprocess Communication.
1842 Returns the cosine of EXPR (expressed in radians).
1843 If EXPR is omitted takes cosine of $_.
1844 .Ip "crypt(PLAINTEXT,SALT)" 8 6
1845 Encrypts a string exactly like the crypt() function in the C library.
1846 Useful for checking the password file for lousy passwords.
1847 Only the guys wearing white hats should do this.
1848 .Ip "dbmclose(ASSOC_ARRAY)" 8 6
1849 .Ip "dbmclose ASSOC_ARRAY" 8
1850 Breaks the binding between a dbm file and an associative array.
1851 The values remaining in the associative array are meaningless unless
1852 you happen to want to know what was in the cache for the dbm file.
1853 This function is only useful if you have ndbm.
1854 .Ip "dbmopen(ASSOC,DBNAME,MODE)" 8 6
1855 This binds a dbm or ndbm file to an associative array.
1856 ASSOC is the name of the associative array.
1857 (Unlike normal open, the first argument is NOT a filehandle, even though
1859 DBNAME is the name of the database (without the .dir or .pag extension).
1860 If the database does not exist, it is created with protection specified
1861 by MODE (as modified by the umask).
1862 If your system only supports the older dbm functions, you may perform only one
1863 dbmopen in your program.
1864 If your system has neither dbm nor ndbm, calling dbmopen produces a fatal
1867 Values assigned to the associative array prior to the dbmopen are lost.
1868 A certain number of values from the dbm file are cached in memory.
1869 By default this number is 64, but you can increase it by preallocating
1870 that number of garbage entries in the associative array before the dbmopen.
1871 You can flush the cache if necessary with the reset command.
1873 If you don't have write access to the dbm file, you can only read
1874 associative array variables, not set them.
1875 If you want to test whether you can write, either use file tests or
1876 try setting a dummy array entry inside an eval, which will trap the error.
1878 Note that functions such as keys() and values() may return huge array values
1879 when used on large dbm files.
1880 You may prefer to use the each() function to iterate over large dbm files.
1885 # print out history file offsets
1886 dbmopen(HIST,'/usr/lib/news/history',0666);
1887 while (($key,$val) = each %HIST) {
1888 print $key, ' = ', unpack('L',$val), "\en";
1893 .Ip "defined(EXPR)" 8 6
1894 .Ip "defined EXPR" 8
1895 Returns a boolean value saying whether the lvalue EXPR has a real value
1897 Many operations return the undefined value under exceptional conditions,
1898 such as end of file, uninitialized variable, system error and such.
1899 This function allows you to distinguish between an undefined null string
1900 and a defined null string with operations that might return a real null
1901 string, in particular referencing elements of an array.
1902 You may also check to see if arrays or subroutines exist.
1903 Use on predefined variables is not guaranteed to produce intuitive results.
1908 print if defined $switch{'D'};
1909 print "$val\en" while defined($val = pop(@ary));
1910 die "Can't readlink $sym: $!"
1911 unless defined($value = readlink $sym);
1912 eval '@foo = ()' if defined(@foo);
1913 die "No XYZ package defined" unless defined %_XYZ;
1914 sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
1918 .Ip "delete $ASSOC{KEY}" 8 6
1919 Deletes the specified value from the specified associative array.
1920 Returns the deleted value, or the undefined value if nothing was deleted.
1921 Deleting from $ENV{} modifies the environment.
1922 Deleting from an array bound to a dbm file deletes the entry from the dbm
1925 The following deletes all the values of an associative array:
1929 foreach $key (keys %ARRAY) {
1930 delete $ARRAY{$key};
1934 (But it would be faster to use the
1937 Saying undef %ARRAY is faster yet.)
1940 Outside of an eval, prints the value of LIST to
1942 and exits with the current value of $!
1944 If $! is 0, exits with the value of ($? >> 8) (\`command\` status).
1945 If ($? >> 8) is 0, exits with 255.
1946 Inside an eval, the error message is stuffed into $@ and the eval is terminated
1947 with the undefined value.
1949 Equivalent examples:
1954 die "Can't cd to spool: $!\en" unless chdir \'/usr/spool/news\';
1957 die "Can't cd to spool: $!\en"
1958 unless chdir \'/usr/spool/news\';
1961 chdir \'/usr/spool/news\' || die "Can't cd to spool: $!\en"
1965 If the value of EXPR does not end in a newline, the current script line
1966 number and input line number (if any) are also printed, and a newline is
1968 Hint: sometimes appending \*(L", stopped\*(R" to your message will cause it to make
1969 better sense when the string \*(L"at foo line 123\*(R" is appended.
1970 Suppose you are running script \*(L"canasta\*(R".
1974 die "/etc/games is no good";
1975 die "/etc/games is no good, stopped";
1977 produce, respectively
1979 /etc/games is no good at canasta line 123.
1980 /etc/games is no good, stopped at canasta line 123.
1986 Returns the value of the last command in the sequence of commands indicated
1988 When modified by a loop modifier, executes the BLOCK once before testing the
1990 (On other statements the loop modifiers test the conditional first.)
1991 .Ip "do SUBROUTINE (LIST)" 8 3
1992 Executes a SUBROUTINE declared by a
1994 declaration, and returns the value
1995 of the last expression evaluated in SUBROUTINE.
1996 If there is no subroutine by that name, produces a fatal error.
1997 (You may use the \*(L"defined\*(R" operator to determine if a subroutine
1999 If you pass arrays as part of LIST you may wish to pass the length
2000 of the array in front of each array.
2001 (See the section on subroutines later on.)
2002 The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R"
2005 SUBROUTINE may also be a single scalar variable, in which case
2006 the name of the subroutine to execute is taken from the variable.
2008 As an alternate (and preferred) form,
2009 you may call a subroutine by prefixing the name with
2010 an ampersand: &foo(@args).
2011 If you aren't passing any arguments, you don't have to use parentheses.
2012 If you omit the parentheses, no @_ array is passed to the subroutine.
2013 The & form is also used to specify subroutines to the defined and undef
2017 if (defined &$var) { &$var($parm); undef &$var; }
2021 Uses the value of EXPR as a filename and executes the contents of the file
2025 Its primary use is to include subroutines from a
2034 eval \`cat stat.pl\`;
2037 except that it's more efficient, more concise, keeps track of the current
2038 filename for error messages, and searches all the
2040 libraries if the file
2041 isn't in the current directory (see also the @INC array in Predefined Names).
2042 It's the same, however, in that it does reparse the file every time you
2043 call it, so if you are going to use the file inside a loop you might prefer
2044 to use \-P and #include, at the expense of a little more startup time.
2045 (The main problem with #include is that cpp doesn't grok # comments\*(--a
2046 workaround is to use \*(L";#\*(R" for standalone comments.)
2047 Note that the following are NOT equivalent:
2051 do $foo; # eval a file
2052 do $foo(); # call a subroutine
2055 Note that inclusion of library routines is better done with
2056 the \*(L"require\*(R" operator.
2057 .Ip "dump LABEL" 8 6
2058 This causes an immediate core dump.
2059 Primarily this is so that you can use the undump program to turn your
2060 core dump into an executable binary after having initialized all your
2061 variables at the beginning of the program.
2062 When the new binary is executed it will begin by executing a "goto LABEL"
2063 (with all the restrictions that goto suffers).
2064 Think of it as a goto with an intervening core dump and reincarnation.
2065 If LABEL is omitted, restarts the program from the top.
2066 WARNING: any files opened at the time of the dump will NOT be open any more
2067 when the program is reincarnated, with possible resulting confusion on the part
2076 require 'getopt.pl';
2087 dump QUICKSTART if $ARGV[0] eq '-d';
2093 .Ip "each(ASSOC_ARRAY)" 8 6
2094 .Ip "each ASSOC_ARRAY" 8
2095 Returns a 2 element array consisting of the key and value for the next
2096 value of an associative array, so that you can iterate over it.
2097 Entries are returned in an apparently random order.
2098 When the array is entirely read, a null array is returned (which when
2099 assigned produces a FALSE (0) value).
2100 The next call to each() after that will start iterating again.
2101 The iterator can be reset only by reading all the elements from the array.
2102 You must not modify the array while iterating over it.
2103 There is a single iterator for each associative array, shared by all
2104 each(), keys() and values() function calls in the program.
2105 The following prints out your environment like the printenv program, only
2106 in a different order:
2110 while (($key,$value) = each %ENV) {
2111 print "$key=$value\en";
2115 See also keys() and values().
2116 .Ip "eof(FILEHANDLE)" 8 8
2119 Returns 1 if the next read on FILEHANDLE will return end of file, or if
2120 FILEHANDLE is not open.
2121 FILEHANDLE may be an expression whose value gives the real filehandle name.
2122 (Note that this function actually reads a character and then ungetc's it,
2123 so it is not very useful in an interactive context.)
2124 An eof without an argument returns the eof status for the last file read.
2125 Empty parentheses () may be used to indicate the pseudo file formed of the
2126 files listed on the command line, i.e. eof() is reasonable to use inside
2127 a while (<>) loop to detect the end of only the last file.
2128 Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop.
2133 # insert dashes just before last line of last file
2136 print "\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\en";
2142 # reset line numbering on each input file
2145 if (eof) { # Not eof().
2151 .Ip "eval(EXPR)" 8 6
2153 .Ip "eval BLOCK" 8 6
2154 EXPR is parsed and executed as if it were a little
2157 It is executed in the context of the current
2160 any variable settings, subroutine or format definitions remain afterwards.
2161 The value returned is the value of the last expression evaluated, just
2162 as with subroutines.
2163 If there is a syntax error or runtime error, or a die statement is
2164 executed, an undefined value is returned by
2165 eval, and $@ is set to the error message.
2166 If there was no error, $@ is guaranteed to be a null string.
2167 If EXPR is omitted, evaluates $_.
2168 The final semicolon, if any, may be omitted from the expression.
2170 Note that, since eval traps otherwise-fatal errors, it is useful for
2171 determining whether a particular feature
2172 (such as dbmopen or symlink) is implemented.
2173 It is also Perl's exception trapping mechanism, where the die operator is
2174 used to raise exceptions.
2176 If the code to be executed doesn't vary, you may use
2177 the eval-BLOCK form to trap run-time errors without incurring
2178 the penalty of recompiling each time.
2179 The error, if any, is still returned in $@.
2180 Evaluating a single-quoted string (as EXPR) has the same effect, except that
2181 the eval-EXPR form reports syntax errors at run time via $@, whereas the
2182 eval-BLOCK form reports syntax errors at compile time. The eval-EXPR form
2183 is optimized to eval-BLOCK the first time it succeeds. (Since the replacement
2184 side of a substitution is considered a single-quoted string when you
2185 use the e modifier, the same optimization occurs there.) Examples:
2189 # make divide-by-zero non-fatal
2190 eval { $answer = $a / $b; }; warn $@ if $@;
2192 # optimized to same thing after first use
2193 eval '$answer = $a / $b'; warn $@ if $@;
2195 # a compile-time error
2199 eval '$answer ='; # sets $@
2202 .Ip "exec(LIST)" 8 8
2204 If there is more than one argument in LIST, or if LIST is an array with
2205 more than one value,
2206 calls execvp() with the arguments in LIST.
2207 If there is only one scalar argument, the argument is checked for shell metacharacters.
2208 If there are any, the entire argument is passed to \*(L"/bin/sh \-c\*(R" for parsing.
2209 If there are none, the argument is split into words and passed directly to
2210 execvp(), which is more efficient.
2211 Note: exec (and system) do not flush your output buffer, so you may need to
2212 set $| to avoid lost output.
2216 exec \'/bin/echo\', \'Your arguments are: \', @ARGV;
2217 exec "sort $outfile | uniq";
2221 If you don't really want to execute the first argument, but want to lie
2222 to the program you are executing about its own name, you can specify
2223 the program you actually want to run by assigning that to a variable and
2224 putting the name of the variable in front of the LIST without a comma.
2225 (This always forces interpretation of the LIST as a multi-valued list, even
2226 if there is only a single scalar in the list.)
2231 $shell = '/bin/csh';
2232 exec $shell '-sh'; # pretend it's a login shell
2235 .Ip "exit(EXPR)" 8 6
2237 Evaluates EXPR and exits immediately with that value.
2243 exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;
2248 If EXPR is omitted, exits with 0 status.
2253 to the power of EXPR.
2254 If EXPR is omitted, gives exp($_).
2255 .Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
2256 Implements the fcntl(2) function.
2257 You'll probably have to say
2260 require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
2263 first to get the correct function definitions.
2264 If fcntl.ph doesn't exist or doesn't have the correct definitions
2266 your own, based on your C header files such as <sys/fcntl.h>.
2267 (There is a perl script called h2ph that comes with the perl kit
2268 which may help you in this.)
2269 Argument processing and value return works just like ioctl below.
2270 Note that fcntl will produce a fatal error if used on a machine that doesn't implement
2272 .Ip "fileno(FILEHANDLE)" 8 4
2273 .Ip "fileno FILEHANDLE" 8 4
2274 Returns the file descriptor for a filehandle.
2275 Useful for constructing bitmaps for select().
2276 If FILEHANDLE is an expression, the value is taken as the name of
2278 .Ip "flock(FILEHANDLE,OPERATION)" 8 4
2279 Calls flock(2) on FILEHANDLE.
2280 See manual page for flock(2) for definition of OPERATION.
2281 Returns true for success, false on failure.
2282 Will produce a fatal error if used on a machine that doesn't implement
2284 Here's a mailbox appender for BSD systems.
2294 flock(MBOX,$LOCK_EX);
2295 # and, in case someone appended
2296 # while we were waiting...
2301 flock(MBOX,$LOCK_UN);
2304 open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
2305 || die "Can't open mailbox: $!";
2308 print MBOX $msg,"\en\en";
2314 Returns the child pid to the parent process and 0 to the child process.
2315 Note: unflushed buffers remain unflushed in both processes, which means
2316 you may need to set $| to avoid duplicate output.
2317 .Ip "getc(FILEHANDLE)" 8 4
2318 .Ip "getc FILEHANDLE" 8
2320 Returns the next character from the input file attached to FILEHANDLE, or
2321 a null string at EOF.
2322 If FILEHANDLE is omitted, reads from STDIN.
2324 Returns the current login from /etc/utmp, if any.
2325 If null, use getpwuid.
2327 $login = getlogin || (getpwuid($<))[0] || "Somebody";
2329 .Ip "getpeername(SOCKET)" 8 3
2330 Returns the packed sockaddr address of other end of the SOCKET connection.
2334 # An internet sockaddr
2335 $sockaddr = 'S n a4 x8';
2336 $hersockaddr = getpeername(S);
2338 ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
2341 ($family, $port, $heraddr) =
2342 unpack($sockaddr,$hersockaddr);
2346 .Ip "getpgrp(PID)" 8 4
2348 Returns the current process group for the specified PID, 0 for the current
2350 Will produce a fatal error if used on a machine that doesn't implement
2352 If EXPR is omitted, returns process group of current process.
2354 Returns the process id of the parent process.
2355 .Ip "getpriority(WHICH,WHO)" 8 4
2356 Returns the current priority for a process, a process group, or a user.
2357 (See getpriority(2).)
2358 Will produce a fatal error if used on a machine that doesn't implement
2360 .Ip "getpwnam(NAME)" 8
2361 .Ip "getgrnam(NAME)" 8
2362 .Ip "gethostbyname(NAME)" 8
2363 .Ip "getnetbyname(NAME)" 8
2364 .Ip "getprotobyname(NAME)" 8
2365 .Ip "getpwuid(UID)" 8
2366 .Ip "getgrgid(GID)" 8
2367 .Ip "getservbyname(NAME,PROTO)" 8
2368 .Ip "gethostbyaddr(ADDR,ADDRTYPE)" 8
2369 .Ip "getnetbyaddr(ADDR,ADDRTYPE)" 8
2370 .Ip "getprotobynumber(NUMBER)" 8
2371 .Ip "getservbyport(PORT,PROTO)" 8
2380 .Ip "sethostent(STAYOPEN)" 8
2381 .Ip "setnetent(STAYOPEN)" 8
2382 .Ip "setprotoent(STAYOPEN)" 8
2383 .Ip "setservent(STAYOPEN)" 8
2390 These routines perform the same functions as their counterparts in the
2392 The return values from the various get routines are as follows:
2395 ($name,$passwd,$uid,$gid,
2396 $quota,$comment,$gcos,$dir,$shell) = getpw.\|.\|.
2397 ($name,$passwd,$gid,$members) = getgr.\|.\|.
2398 ($name,$aliases,$addrtype,$length,@addrs) = gethost.\|.\|.
2399 ($name,$aliases,$addrtype,$net) = getnet.\|.\|.
2400 ($name,$aliases,$proto) = getproto.\|.\|.
2401 ($name,$aliases,$port,$proto) = getserv.\|.\|.
2404 The $members value returned by getgr.\|.\|. is a space separated list
2405 of the login names of the members of the group.
2407 The @addrs value returned by the gethost.\|.\|. functions is a list of the
2408 raw addresses returned by the corresponding system library call.
2409 In the Internet domain, each address is four bytes long and you can unpack
2410 it by saying something like:
2413 ($a,$b,$c,$d) = unpack('C4',$addr[0]);
2416 .Ip "getsockname(SOCKET)" 8 3
2417 Returns the packed sockaddr address of this end of the SOCKET connection.
2421 # An internet sockaddr
2422 $sockaddr = 'S n a4 x8';
2423 $mysockaddr = getsockname(S);
2425 ($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr);
2428 ($family, $port, $myaddr) =
2429 unpack($sockaddr,$mysockaddr);
2433 .Ip "getsockopt(SOCKET,LEVEL,OPTNAME)" 8 3
2434 Returns the socket option requested, or undefined if there is an error.
2435 .Ip "gmtime(EXPR)" 8 4
2437 Converts a time as returned by the time function to a 9-element array with
2438 the time analyzed for the Greenwich timezone.
2439 Typically used as follows:
2444 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
2447 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
2452 All array elements are numeric, and come straight out of a struct tm.
2453 In particular this means that $mon has the range 0.\|.11 and $wday has the
2455 If EXPR is omitted, does gmtime(time).
2456 .Ip "goto LABEL" 8 6
2457 Finds the statement labeled with LABEL and resumes execution there.
2458 Currently you may only go to statements in the main body of the program
2459 that are not nested inside a do {} construct.
2460 This statement is not implemented very efficiently, and is here only to make
2464 I may change its semantics at any time, consistent with support for translated
2467 Use it at your own risk.
2468 Better yet, don't use it at all.
2469 .Ip "grep(EXPR,LIST)" 8 4
2470 Evaluates EXPR for each element of LIST (locally setting $_ to each element)
2471 and returns the array value consisting of those elements for which the
2472 expression evaluated to true.
2473 In a scalar context, returns the number of times the expression was true.
2476 @foo = grep(!/^#/, @bar); # weed out comments
2479 Note that, since $_ is a reference into the array value, it can be
2480 used to modify the elements of the array.
2481 While this is useful and supported, it can cause bizarre results if
2482 the LIST is not a named array.
2485 Returns the decimal value of EXPR interpreted as an hex string.
2486 (To interpret strings that might start with 0 or 0x see oct().)
2487 If EXPR is omitted, uses $_.
2488 .Ip "index(STR,SUBSTR,POSITION)" 8 4
2489 .Ip "index(STR,SUBSTR)" 8 4
2490 Returns the position of the first occurrence of SUBSTR in STR at or after
2492 If POSITION is omitted, starts searching from the beginning of the string.
2493 The return value is based at 0, or whatever you've
2494 set the $[ variable to.
2495 If the substring is not found, returns one less than the base, ordinarily \-1.
2498 Returns the integer portion of EXPR.
2499 If EXPR is omitted, uses $_.
2500 .Ip "ioctl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
2501 Implements the ioctl(2) function.
2502 You'll probably have to say
2505 require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
2508 first to get the correct function definitions.
2509 If ioctl.ph doesn't exist or doesn't have the correct definitions
2511 your own, based on your C header files such as <sys/ioctl.h>.
2512 (There is a perl script called h2ph that comes with the perl kit
2513 which may help you in this.)
2514 SCALAR will be read and/or written depending on the FUNCTION\*(--a pointer
2515 to the string value of SCALAR will be passed as the third argument of
2516 the actual ioctl call.
2517 (If SCALAR has no string value but does have a numeric value, that value
2518 will be passed rather than a pointer to the string value.
2519 To guarantee this to be true, add a 0 to the scalar before using it.)
2520 The pack() and unpack() functions are useful for manipulating the values
2521 of structures used by ioctl().
2522 The following example sets the erase character to DEL.
2527 $sgttyb_t = "ccccs"; # 4 chars and a short
2528 if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
2529 @ary = unpack($sgttyb_t,$sgttyb);
2531 $sgttyb = pack($sgttyb_t,@ary);
2532 ioctl(STDIN,$TIOCSETP,$sgttyb)
2533 || die "Can't ioctl: $!";
2537 The return value of ioctl (and fcntl) is as follows:
2541 if OS returns:\h'|3i'perl returns:
2542 -1\h'|3i' undefined value
2543 0\h'|3i' string "0 but true"
2544 anything else\h'|3i' that number
2547 Thus perl returns true on success and false on failure, yet you can still
2548 easily determine the actual value returned by the operating system:
2551 ($retval = ioctl(...)) || ($retval = -1);
2552 printf "System returned %d\en", $retval;
2554 .Ip "join(EXPR,LIST)" 8 8
2555 .Ip "join(EXPR,ARRAY)" 8
2556 Joins the separate strings of LIST or ARRAY into a single string with fields
2557 separated by the value of EXPR, and returns the string.
2562 $_ = join(\|\':\', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
2566 $login,$passwd,$uid,$gid,$gcos,$home,$shell);
2572 .Ip "keys(ASSOC_ARRAY)" 8 6
2573 .Ip "keys ASSOC_ARRAY" 8
2574 Returns a normal array consisting of all the keys of the named associative
2576 The keys are returned in an apparently random order, but it is the same order
2577 as either the values() or each() function produces (given that the associative array
2578 has not been modified).
2579 Here is yet another way to print your environment:
2584 @values = values %ENV;
2585 while ($#keys >= 0) {
2586 print pop(@keys), \'=\', pop(@values), "\en";
2589 or how about sorted by key:
2592 foreach $key (sort(keys %ENV)) {
2593 print $key, \'=\', $ENV{$key}, "\en";
2597 .Ip "kill(LIST)" 8 8
2599 Sends a signal to a list of processes.
2600 The first element of the list must be the signal to send.
2601 Returns the number of processes successfully signaled.
2604 $cnt = kill 1, $child1, $child2;
2608 If the signal is negative, kills process groups instead of processes.
2609 (On System V, a negative \fIprocess\fR number will also kill process groups,
2610 but that's not portable.)
2611 You may use a signal name in quotes.
2612 .Ip "last LABEL" 8 8
2618 statement in C (as used in loops); it immediately exits the loop in question.
2619 If the LABEL is omitted, the command refers to the innermost enclosing loop.
2622 block, if any, is not executed:
2626 line: while (<STDIN>) {
2627 last line if /\|^$/; # exit when done with header
2632 .Ip "length(EXPR)" 8 4
2634 Returns the length in characters of the value of EXPR.
2635 If EXPR is omitted, returns length of $_.
2636 .Ip "link(OLDFILE,NEWFILE)" 8 2
2637 Creates a new filename linked to the old filename.
2638 Returns 1 for success, 0 otherwise.
2639 .Ip "listen(SOCKET,QUEUESIZE)" 8 2
2640 Does the same thing that the listen system call does.
2641 Returns true if it succeeded, false otherwise.
2642 See example in section on Interprocess Communication.
2643 .Ip "local(LIST)" 8 4
2644 Declares the listed variables to be local to the enclosing block,
2645 subroutine, eval or \*(L"do\*(R".
2646 All the listed elements must be legal lvalues.
2647 This operator works by saving the current values of those variables in LIST
2648 on a hidden stack and restoring them upon exiting the block, subroutine or eval.
2649 This means that called subroutines can also reference the local variable,
2650 but not the global one.
2651 The LIST may be assigned to if desired, which allows you to initialize
2652 your local variables.
2653 (If no initializer is given for a particular variable, it is created with
2654 an undefined value.)
2655 Commonly this is used to name the parameters to a subroutine.
2661 local($min, $max, $thunk) = @_;
2662 local($result) = \'\';
2665 # Presumably $thunk makes reference to $i
2667 for ($i = $min; $i < $max; $i++) {
2668 $result .= eval $thunk;
2675 if ($sw eq \'-v\') {
2676 # init local array with global array
2677 local(@ARGV) = @ARGV;
2678 unshift(@ARGV,\'echo\');
2684 # temporarily add to digits associative array
2686 # (NOTE: not claiming this is efficient!)
2687 local(%digits) = (%digits,'t',10,'e',11);
2692 Note that local() is a run-time command, and so gets executed every time
2693 through a loop, using up more stack storage each time until it's all
2694 released at once when the loop is exited.
2695 .Ip "localtime(EXPR)" 8 4
2696 .Ip "localtime EXPR" 8
2697 Converts a time as returned by the time function to a 9-element array with
2698 the time analyzed for the local timezone.
2699 Typically used as follows:
2704 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
2707 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
2712 All array elements are numeric, and come straight out of a struct tm.
2713 In particular this means that $mon has the range 0.\|.11 and $wday has the
2715 If EXPR is omitted, does localtime(time).
2718 Returns logarithm (base
2721 If EXPR is omitted, returns log of $_.
2722 .Ip "lstat(FILEHANDLE)" 8 6
2723 .Ip "lstat FILEHANDLE" 8
2725 .Ip "lstat SCALARVARIABLE" 8
2726 Does the same thing as the stat() function, but stats a symbolic link
2727 instead of the file the symbolic link points to.
2728 If symbolic links are unimplemented on your system, a normal stat is done.
2729 .Ip "m/PATTERN/gio" 8 4
2730 .Ip "/PATTERN/gio" 8
2731 Searches a string for a pattern match, and returns true (1) or false (\'\').
2732 If no string is specified via the =~ or !~ operator,
2733 the $_ string is searched.
2734 (The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
2735 See also the section on regular expressions.
2737 If / is the delimiter then the initial \*(L'm\*(R' is optional.
2738 With the \*(L'm\*(R' you can use any pair of non-alphanumeric characters
2740 This is particularly useful for matching Unix path names that contain \*(L'/\*(R'.
2741 If the final delimiter is followed by the optional letter \*(L'i\*(R', the matching is
2742 done in a case-insensitive manner.
2743 PATTERN may contain references to scalar variables, which will be interpolated
2744 (and the pattern recompiled) every time the pattern search is evaluated.
2745 (Note that $) and $| may not be interpolated because they look like end-of-string tests.)
2746 If you want such a pattern to be compiled only once, add an \*(L"o\*(R" after
2747 the trailing delimiter.
2748 This avoids expensive run-time recompilations, and
2749 is useful when the value you are interpolating won't change over the
2751 If the PATTERN evaluates to a null string, the most recent successful
2752 regular expression is used instead.
2754 If used in a context that requires an array value, a pattern match returns an
2755 array consisting of the subexpressions matched by the parentheses in the
2757 i.e. ($1, $2, $3.\|.\|.).
2758 It does NOT actually set $1, $2, etc. in this case, nor does it set $+, $`, $&
2760 If the match fails, a null array is returned.
2761 If the match succeeds, but there were no parentheses, an array value of (1)
2768 open(tty, \'/dev/tty\');
2769 <tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|); # do foo if desired
2771 if (/Version: \|*\|([0\-9.]*\|)\|/\|) { $version = $1; }
2773 next if m#^/usr/spool/uucp#;
2779 print if /$arg/o; # compile only once
2782 if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/))
2785 This last example splits $foo into the first two words and the remainder
2786 of the line, and assigns those three fields to $F1, $F2 and $Etc.
2787 The conditional is true if any variables were assigned, i.e. if the pattern
2790 The \*(L"g\*(R" modifier specifies global pattern matching\*(--that is,
2791 matching as many times as possible within the string. How it behaves
2792 depends on the context. In an array context, it returns a list of
2793 all the substrings matched by all the parentheses in the regular expression.
2794 If there are no parentheses, it returns a list of all the matched strings,
2795 as if there were parentheses around the whole pattern. In a scalar context,
2796 it iterates through the string, returning TRUE each time it matches, and
2797 FALSE when it eventually runs out of matches. (In other words, it remembers
2798 where it left off last time and restarts the search at that point.) It
2799 presumes that you have not modified the string since the last match.
2800 Modifying the string between matches may result in undefined behavior.
2801 (You can actually get away with in-place modifications via substr()
2802 that do not change the length of the entire string. In general, however,
2803 you should be using s///g for such modifications.) Examples:
2807 ($one,$five,$fifteen) = (\`uptime\` =~ /(\ed+\e.\ed+)/g);
2811 while ($paragraph = <>) {
2812 while ($paragraph =~ /[a-z][\'")]*[.!?]+[\'")]*\es/g) {
2816 print "$sentences\en";
2819 .Ip "mkdir(FILENAME,MODE)" 8 3
2820 Creates the directory specified by FILENAME, with permissions specified by
2821 MODE (as modified by umask).
2822 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
2823 .Ip "msgctl(ID,CMD,ARG)" 8 4
2824 Calls the System V IPC function msgctl. If CMD is &IPC_STAT, then ARG
2825 must be a variable which will hold the returned msqid_ds structure.
2826 Returns like ioctl: the undefined value for error, "0 but true" for
2827 zero, or the actual return value otherwise.
2828 .Ip "msgget(KEY,FLAGS)" 8 4
2829 Calls the System V IPC function msgget. Returns the message queue id,
2830 or the undefined value if there is an error.
2831 .Ip "msgsnd(ID,MSG,FLAGS)" 8 4
2832 Calls the System V IPC function msgsnd to send the message MSG to the
2833 message queue ID. MSG must begin with the long integer message type,
2834 which may be created with pack("L", $type). Returns true if
2835 successful, or false if there is an error.
2836 .Ip "msgrcv(ID,VAR,SIZE,TYPE,FLAGS)" 8 4
2837 Calls the System V IPC function msgrcv to receive a message from
2838 message queue ID into variable VAR with a maximum message size of
2839 SIZE. Note that if a message is received, the message type will be
2840 the first thing in VAR, and the maximum length of VAR is SIZE plus the
2841 size of the message type. Returns true if successful, or false if
2843 .Ip "next LABEL" 8 8
2849 statement in C; it starts the next iteration of the loop:
2853 line: while (<STDIN>) {
2854 next line if /\|^#/; # discard comments
2859 Note that if there were a
2861 block on the above, it would get executed even on discarded lines.
2862 If the LABEL is omitted, the command refers to the innermost enclosing loop.
2865 Returns the decimal value of EXPR interpreted as an octal string.
2866 (If EXPR happens to start off with 0x, interprets it as a hex string instead.)
2867 The following will handle decimal, octal and hex in the standard notation:
2870 $val = oct($val) if $val =~ /^0/;
2873 If EXPR is omitted, uses $_.
2874 .Ip "open(FILEHANDLE,EXPR)" 8 8
2875 .Ip "open(FILEHANDLE)" 8
2876 .Ip "open FILEHANDLE" 8
2877 Opens the file whose filename is given by EXPR, and associates it with
2879 If FILEHANDLE is an expression, its value is used as the name of the
2880 real filehandle wanted.
2881 If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
2882 contains the filename.
2883 If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
2885 If the filename begins with \*(L">\*(R", the file is opened for output.
2886 If the filename begins with \*(L">>\*(R", the file is opened for appending.
2887 (You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
2888 want both read and write access to the file.)
2889 If the filename begins with \*(L"|\*(R", the filename is interpreted
2890 as a command to which output is to be piped, and if the filename ends
2891 with a \*(L"|\*(R", the filename is interpreted as command which pipes
2893 (You may not have a command that pipes both in and out.)
2894 Opening \'\-\' opens
2896 and opening \'>\-\' opens
2898 Open returns non-zero upon success, the undefined value otherwise.
2899 If the open involved a pipe, the return value happens to be the pid
2906 open article || die "Can't find article $article: $!\en";
2907 while (<article>) {\|.\|.\|.
2910 open(LOG, \'>>/usr/spool/news/twitlog\'\|); # (log is reserved)
2913 open(LOG, \'>>/usr/spool/news/twitlog\'\|);
2918 open(article, "caesar <$article |"\|); # decrypt article
2921 open(article, "caesar <$article |"\|);
2926 open(extract, "|sort >/tmp/Tmp$$"\|); # $$ is our process#
2929 open(extract, "|sort >/tmp/Tmp$$"\|);
2930 # $$ is our process#
2934 # process argument list of files along with any includes
2936 foreach $file (@ARGV) {
2937 do process($file, \'fh00\'); # no pun intended
2941 local($filename, $input) = @_;
2942 $input++; # this is a string increment
2943 unless (open($input, $filename)) {
2944 print STDERR "Can't open $filename: $!\en";
2948 while (<$input>) { # note the use of indirection
2951 while (<$input>) { # note use of indirection
2953 if (/^#include "(.*)"/) {
2954 do process($1, $input);
2962 You may also, in the Bourne shell tradition, specify an EXPR beginning
2963 with \*(L">&\*(R", in which case the rest of the string
2964 is interpreted as the name of a filehandle
2965 (or file descriptor, if numeric) which is to be duped and opened.
2966 You may use & after >, >>, <, +>, +>> and +<.
2967 The mode you specify should match the mode of the original filehandle.
2968 Here is a script that saves, redirects, and restores
2976 open(SAVEOUT, ">&STDOUT");
2977 open(SAVEERR, ">&STDERR");
2979 open(STDOUT, ">foo.out") || die "Can't redirect stdout";
2980 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
2982 select(STDERR); $| = 1; # make unbuffered
2983 select(STDOUT); $| = 1; # make unbuffered
2985 print STDOUT "stdout 1\en"; # this works for
2986 print STDERR "stderr 1\en"; # subprocesses too
2991 open(STDOUT, ">&SAVEOUT");
2992 open(STDERR, ">&SAVEERR");
2994 print STDOUT "stdout 2\en";
2995 print STDERR "stderr 2\en";
2998 If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
2999 then there is an implicit fork done, and the return value of open
3000 is the pid of the child within the parent process, and 0 within the child
3002 (Use defined($pid) to determine if the open was successful.)
3003 The filehandle behaves normally for the parent, but i/o to that
3004 filehandle is piped from/to the
3006 of the child process.
3007 In the child process the filehandle isn't opened\*(--i/o happens from/to
3012 Typically this is used like the normal piped open when you want to exercise
3013 more control over just how the pipe command gets executed, such as when
3014 you are running setuid, and don't want to have to scan shell commands
3016 The following pairs are more or less equivalent:
3020 open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
3021 open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
3023 open(FOO, "cat \-n '$file'|");
3024 open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
3027 Explicitly closing any piped filehandle causes the parent process to wait for the
3028 child to finish, and returns the status value in $?.
3029 Note: on any operation which may do a fork,
3030 unflushed buffers remain unflushed in both
3031 processes, which means you may need to set $| to
3032 avoid duplicate output.
3034 The filename that is passed to open will have leading and trailing
3036 In order to open a file with arbitrary weird characters in it, it's necessary
3037 to protect any leading and trailing whitespace thusly:
3041 $file =~ s#^(\es)#./$1#;
3042 open(FOO, "< $file\e0");
3045 .Ip "opendir(DIRHANDLE,EXPR)" 8 3
3046 Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
3047 rewinddir() and closedir().
3048 Returns true if successful.
3049 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
3052 Returns the numeric ascii value of the first character of EXPR.
3053 If EXPR is omitted, uses $_.
3054 ''' Comments on f & d by gnb@melba.bby.oz.au 22/11/89
3055 .Ip "pack(TEMPLATE,LIST)" 8 4
3056 Takes an array or list of values and packs it into a binary structure,
3057 returning the string containing the structure.
3058 The TEMPLATE is a sequence of characters that give the order and type
3059 of values, as follows:
3062 A An ascii string, will be space padded.
3063 a An ascii string, will be null padded.
3064 c A signed char value.
3065 C An unsigned char value.
3066 s A signed short value.
3067 S An unsigned short value.
3068 i A signed integer value.
3069 I An unsigned integer value.
3070 l A signed long value.
3071 L An unsigned long value.
3072 n A short in \*(L"network\*(R" order.
3073 N A long in \*(L"network\*(R" order.
3074 f A single-precision float in the native format.
3075 d A double-precision float in the native format.
3076 p A pointer to a string.
3077 v A short in \*(L"VAX\*(R" (little-endian) order.
3078 V A long in \*(L"VAX\*(R" (little-endian) order.
3081 @ Null fill to absolute position.
3082 u A uuencoded string.
3083 b A bit string (ascending bit order, like vec()).
3084 B A bit string (descending bit order).
3085 h A hex string (low nybble first).
3086 H A hex string (high nybble first).
3089 Each letter may optionally be followed by a number which gives a repeat
3091 With all types except "a", "A", "b", "B", "h" and "H",
3092 the pack function will gobble up that many values
3094 A * for the repeat count means to use however many items are left.
3095 The "a" and "A" types gobble just one value, but pack it as a string of length
3097 padding with nulls or spaces as necessary.
3098 (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
3099 Likewise, the "b" and "B" fields pack a string that many bits long.
3100 The "h" and "H" fields pack a string that many nybbles long.
3101 Real numbers (floats and doubles) are in the native machine format
3102 only; due to the multiplicity of floating formats around, and the lack
3103 of a standard \*(L"network\*(R" representation, no facility for
3104 interchange has been made.
3105 This means that packed floating point data
3106 written on one machine may not be readable on another - even if both
3107 use IEEE floating point arithmetic (as the endian-ness of the memory
3108 representation is not part of the IEEE spec).
3110 doubles internally for all numeric calculation, and converting from
3111 double -> float -> double will lose precision (i.e. unpack("f",
3112 pack("f", $foo)) will not in general equal $foo).
3117 $foo = pack("cccc",65,66,67,68);
3119 $foo = pack("c4",65,66,67,68);
3122 $foo = pack("ccxxcc",65,66,67,68);
3123 # foo eq "AB\e0\e0CD"
3125 $foo = pack("s2",1,2);
3126 # "\e1\e0\e2\e0" on little-endian
3127 # "\e0\e1\e0\e2" on big-endian
3129 $foo = pack("a4","abcd","x","y","z");
3132 $foo = pack("aaaa","abcd","x","y","z");
3135 $foo = pack("a14","abcdefg");
3136 # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
3138 $foo = pack("i9pl", gmtime);
3139 # a real struct tm (on my system anyway)
3142 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
3145 The same template may generally also be used in the unpack function.
3146 .Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
3147 Opens a pair of connected pipes like the corresponding system call.
3148 Note that if you set up a loop of piped processes, deadlock can occur
3149 unless you are very careful.
3150 In addition, note that perl's pipes use stdio buffering, so you may need
3151 to set $| to flush your WRITEHANDLE after each command, depending on
3153 [Requires version 3.0 patchlevel 9.]
3156 Pops and returns the last value of the array, shortening the array by 1.
3157 Has the same effect as
3160 $tmp = $ARRAY[$#ARRAY\-\|\-];
3163 If there are no elements in the array, returns the undefined value.
3164 .Ip "print(FILEHANDLE LIST)" 8 10
3166 .Ip "print FILEHANDLE LIST" 8
3169 Prints a string or a comma-separated list of strings.
3170 Returns non-zero if successful.
3171 FILEHANDLE may be a scalar variable name, in which case the variable contains
3172 the name of the filehandle, thus introducing one level of indirection.
3173 (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
3174 misinterpreted as an operator unless you interpose a + or put parens around
3176 If FILEHANDLE is omitted, prints by default to standard output (or to the
3177 last selected output channel\*(--see select()).
3178 If LIST is also omitted, prints $_ to
3180 To set the default output channel to something other than
3182 use the select operation.
3183 Note that, because print takes a LIST, anything in the LIST is evaluated
3184 in an array context, and any subroutine that you call will have one or more
3185 of its expressions evaluated in an array context.
3186 Also be careful not to follow the print keyword with a left parenthesis
3187 unless you want the corresponding right parenthesis to terminate the
3188 arguments to the print\*(--interpose a + or put parens around all the arguments.
3189 .Ip "printf(FILEHANDLE LIST)" 8 10
3190 .Ip "printf(LIST)" 8
3191 .Ip "printf FILEHANDLE LIST" 8
3193 Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
3194 .Ip "push(ARRAY,LIST)" 8 7
3195 Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
3196 onto the end of ARRAY.
3197 The length of ARRAY increases by the length of LIST.
3198 Has the same effect as
3202 $ARRAY[++$#ARRAY] = $value;
3206 but is more efficient.
3210 These are not really functions, but simply syntactic sugar to let you
3211 avoid putting too many backslashes into quoted strings.
3212 The q operator is a generalized single quote, and the qq operator a
3213 generalized double quote.
3214 The qx operator is a generalized backquote.
3215 Any non-alphanumeric delimiter can be used in place of /, including newline.
3216 If the delimiter is an opening bracket or parenthesis, the final delimiter
3217 will be the corresponding closing bracket or parenthesis.
3218 (Embedded occurrences of the closing bracket need to be backslashed as usual.)
3223 $foo = q!I said, "You said, \'She said it.\'"!;
3224 $bar = q(\'This is it.\');
3225 $today = qx{ date };
3227 *** The previous line contains the naughty word "$&".\en
3228 if /(ibm|apple|awk)/; # :-)
3231 .Ip "rand(EXPR)" 8 8
3234 Returns a random fractional number between 0 and the value of EXPR.
3235 (EXPR should be positive.)
3236 If EXPR is omitted, returns a value between 0 and 1.
3238 .Ip "read(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
3239 .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
3240 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
3242 Returns the number of bytes actually read, or undef if there was an error.
3243 SCALAR will be grown or shrunk to the length actually read.
3244 An OFFSET may be specified to place the read data at some other place
3245 than the beginning of the string.
3246 This call is actually implemented in terms of stdio's fread call. To get
3247 a true read system call, see sysread.
3248 .Ip "readdir(DIRHANDLE)" 8 3
3249 .Ip "readdir DIRHANDLE" 8
3250 Returns the next directory entry for a directory opened by opendir().
3251 If used in an array context, returns all the rest of the entries in the
3253 If there are no more entries, returns an undefined value in a scalar context
3254 or a null list in an array context.
3255 .Ip "readlink(EXPR)" 8 6
3256 .Ip "readlink EXPR" 8
3257 Returns the value of a symbolic link, if symbolic links are implemented.
3258 If not, gives a fatal error.
3259 If there is some system error, returns the undefined value and sets $! (errno).
3260 If EXPR is omitted, uses $_.
3261 .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
3262 Receives a message on a socket.
3263 Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
3265 Returns the address of the sender, or the undefined value if there's an error.
3266 SCALAR will be grown or shrunk to the length actually read.
3267 Takes the same flags as the system call of the same name.
3268 .Ip "redo LABEL" 8 8
3272 command restarts the loop block without evaluating the conditional again.
3275 block, if any, is not executed.
3276 If the LABEL is omitted, the command refers to the innermost enclosing loop.
3277 This command is normally used by programs that want to lie to themselves
3278 about what was just input:
3282 # a simpleminded Pascal comment stripper
3283 # (warning: assumes no { or } in strings)
3284 line: while (<STDIN>) {
3285 while (s|\|({.*}.*\|){.*}|$1 \||) {}
3290 if (\|/\|}/\|) { # end of comment?
3300 .Ip "rename(OLDNAME,NEWNAME)" 8 2
3301 Changes the name of a file.
3302 Returns 1 for success, 0 otherwise.
3303 Will not work across filesystem boundaries.
3304 .Ip "require(EXPR)" 8 6
3305 .Ip "require EXPR" 8
3307 Includes the library file specified by EXPR, or by $_ if EXPR is not supplied.
3308 Has semantics similar to the following subroutine:
3312 local($filename) = @_;
3313 return 1 if $INC{$filename};
3314 local($realfilename,$result);
3316 foreach $prefix (@INC) {
3317 $realfilename = "$prefix/$filename";
3318 if (-f $realfilename) {
3319 $result = do $realfilename;
3323 die "Can't find $filename in \e@INC";
3326 die "$filename did not return true value" unless $result;
3327 $INC{$filename} = $realfilename;
3332 Note that the file will not be included twice under the same specified name.
3333 .Ip "reset(EXPR)" 8 6
3338 block at the end of a loop to clear variables and reset ?? searches
3339 so that they work again.
3340 The expression is interpreted as a list of single characters (hyphens allowed
3342 All variables and arrays beginning with one of those letters are reset to
3343 their pristine state.
3344 If the expression is omitted, one-match searches (?pattern?) are reset to
3346 Only resets variables or searches in the current package.
3352 reset \'X\'; \h'|2i'# reset all X variables
3353 reset \'a\-z\';\h'|2i'# reset lower case variables
3354 reset; \h'|2i'# just reset ?? searches
3357 Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
3360 The use of reset on dbm associative arrays does not change the dbm file.
3361 (It does, however, flush any entries cached by perl, which may be useful if
3362 you are sharing the dbm file.
3363 Then again, maybe not.)
3364 .Ip "return LIST" 8 3
3365 Returns from a subroutine with the value specified.
3366 (Note that a subroutine can automatically return
3367 the value of the last expression evaluated.
3368 That's the preferred method\*(--use of an explicit
3371 .Ip "reverse(LIST)" 8 4
3372 .Ip "reverse LIST" 8
3373 In an array context, returns an array value consisting of the elements
3374 of LIST in the opposite order.
3375 In a scalar context, returns a string value consisting of the bytes of
3376 the first element of LIST in the opposite order.
3377 .Ip "rewinddir(DIRHANDLE)" 8 5
3378 .Ip "rewinddir DIRHANDLE" 8
3379 Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
3380 .Ip "rindex(STR,SUBSTR,POSITION)" 8 6
3381 .Ip "rindex(STR,SUBSTR)" 8 4
3382 Works just like index except that it
3383 returns the position of the LAST occurrence of SUBSTR in STR.
3384 If POSITION is specified, returns the last occurrence at or before that
3386 .Ip "rmdir(FILENAME)" 8 4
3387 .Ip "rmdir FILENAME" 8
3388 Deletes the directory specified by FILENAME if it is empty.
3389 If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
3390 If FILENAME is omitted, uses $_.
3391 .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
3392 Searches a string for a pattern, and if found, replaces that pattern with the
3393 replacement text and returns the number of substitutions made.
3394 Otherwise it returns false (0).
3395 The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
3396 of the pattern are to be replaced.
3397 The \*(L"i\*(R" is also optional, and if present, indicates that matching
3398 is to be done in a case-insensitive manner.
3399 The \*(L"e\*(R" is likewise optional, and if present, indicates that
3400 the replacement string is to be evaluated as an expression rather than just
3401 as a double-quoted string.
3402 Any non-alphanumeric delimiter may replace the slashes;
3403 if single quotes are used, no
3404 interpretation is done on the replacement string (the e modifier overrides
3405 this, however); if backquotes are used, the replacement string is a command
3406 to execute whose output will be used as the actual replacement text.
3407 If no string is specified via the =~ or !~ operator,
3408 the $_ string is searched and modified.
3409 (The string specified with =~ must be a scalar variable, an array element,
3410 or an assignment to one of those, i.e. an lvalue.)
3411 If the pattern contains a $ that looks like a variable rather than an
3412 end-of-string test, the variable will be interpolated into the pattern at
3414 If you only want the pattern compiled once the first time the variable is
3415 interpolated, add an \*(L"o\*(R" at the end.
3416 If the PATTERN evaluates to a null string, the most recent successful
3417 regular expression is used instead.
3418 See also the section on regular expressions.
3422 s/\|\e\|bgreen\e\|b/mauve/g; # don't change wintergreen
3424 $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
3426 s/Login: $foo/Login: $bar/; # run-time pattern
3428 ($foo = $bar) =~ s/bar/foo/;
3431 s/\ed+/$&*2/e; # yields \*(L'abc246xyz\*(R'
3432 s/\ed+/sprintf("%5d",$&)/e; # yields \*(L'abc 246xyz\*(R'
3433 s/\ew/$& x 2/eg; # yields \*(L'aabbcc 224466xxyyzz\*(R'
3435 s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/; # reverse 1st two fields
3438 (Note the use of $ instead of \|\e\| in the last example. See section
3439 on regular expressions.)
3440 .Ip "scalar(EXPR)" 8 3
3441 Forces EXPR to be interpreted in a scalar context and returns the value
3443 .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
3444 Randomly positions the file pointer for FILEHANDLE, just like the fseek()
3446 FILEHANDLE may be an expression whose value gives the name of the filehandle.
3447 Returns 1 upon success, 0 otherwise.
3448 .Ip "seekdir(DIRHANDLE,POS)" 8 3
3449 Sets the current position for the readdir() routine on DIRHANDLE.
3450 POS must be a value returned by telldir().
3451 Has the same caveats about possible directory compaction as the corresponding
3452 system library routine.
3453 .Ip "select(FILEHANDLE)" 8 3
3455 Returns the currently selected filehandle.
3456 Sets the current default filehandle for output, if FILEHANDLE is supplied.
3457 This has two effects: first, a
3461 without a filehandle will default to this FILEHANDLE.
3462 Second, references to variables related to output will refer to this output
3464 For example, if you have to set the top of form format for more than
3465 one output channel, you might do the following:
3470 $^ = \'report1_top\';
3472 $^ = \'report2_top\';
3475 FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
3479 $oldfh = select(STDERR); $| = 1; select($oldfh);
3482 .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
3483 This calls the select system call with the bitmasks specified, which can
3484 be constructed using fileno() and vec(), along these lines:
3487 $rin = $win = $ein = '';
3488 vec($rin,fileno(STDIN),1) = 1;
3489 vec($win,fileno(STDOUT),1) = 1;
3493 If you want to select on many filehandles you might wish to write a subroutine:
3497 local(@fhlist) = split(' ',$_[0]);
3500 vec($bits,fileno($_),1) = 1;
3504 $rin = &fhbits('STDIN TTY SOCK');
3510 ($nfound,$timeleft) =
3511 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
3513 or to block until something becomes ready:
3516 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
3519 $nfound = select($rout=$rin, $wout=$win,
3524 Any of the bitmasks can also be undef.
3525 The timeout, if specified, is in seconds, which may be fractional.
3526 NOTE: not all implementations are capable of returning the $timeleft.
3527 If not, they always return $timeleft equal to the supplied $timeout.
3528 .Ip "semctl(ID,SEMNUM,CMD,ARG)" 8 4
3529 Calls the System V IPC function semctl. If CMD is &IPC_STAT or
3530 &GETALL, then ARG must be a variable which will hold the returned
3531 semid_ds structure or semaphore value array. Returns like ioctl: the
3532 undefined value for error, "0 but true" for zero, or the actual return
3534 .Ip "semget(KEY,NSEMS,SIZE,FLAGS)" 8 4
3535 Calls the System V IPC function semget. Returns the semaphore id, or
3536 the undefined value if there is an error.
3537 .Ip "semop(KEY,OPSTRING)" 8 4
3538 Calls the System V IPC function semop to perform semaphore operations
3539 such as signaling and waiting. OPSTRING must be a packed array of
3540 semop structures. Each semop structure can be generated with
3541 \&'pack("sss", $semnum, $semop, $semflag)'. The number of semaphore
3542 operations is implied by the length of OPSTRING. Returns true if
3543 successful, or false if there is an error. As an example, the
3544 following code waits on semaphore $semnum of semaphore id $semid:
3547 $semop = pack("sss", $semnum, -1, 0);
3548 die "Semaphore trouble: $!\en" unless semop($semid, $semop);
3551 To signal the semaphore, replace "-1" with "1".
3552 .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
3553 .Ip "send(SOCKET,MSG,FLAGS)" 8
3554 Sends a message on a socket.
3555 Takes the same flags as the system call of the same name.
3556 On unconnected sockets you must specify a destination to send TO.
3557 Returns the number of characters sent, or the undefined value if
3559 .Ip "setpgrp(PID,PGRP)" 8 4
3560 Sets the current process group for the specified PID, 0 for the current
3562 Will produce a fatal error if used on a machine that doesn't implement
3564 .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
3565 Sets the current priority for a process, a process group, or a user.
3566 (See setpriority(2).)
3567 Will produce a fatal error if used on a machine that doesn't implement
3569 .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
3570 Sets the socket option requested.
3571 Returns undefined if there is an error.
3572 OPTVAL may be specified as undef if you don't want to pass an argument.
3573 .Ip "shift(ARRAY)" 8 6
3576 Shifts the first value of the array off and returns it,
3577 shortening the array by 1 and moving everything down.
3578 If there are no elements in the array, returns the undefined value.
3579 If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
3580 array in subroutines.
3581 (This is determined lexically.)
3582 See also unshift(), push() and pop().
3583 Shift() and unshift() do the same thing to the left end of an array that push()
3584 and pop() do to the right end.
3585 .Ip "shmctl(ID,CMD,ARG)" 8 4
3586 Calls the System V IPC function shmctl. If CMD is &IPC_STAT, then ARG
3587 must be a variable which will hold the returned shmid_ds structure.
3588 Returns like ioctl: the undefined value for error, "0 but true" for
3589 zero, or the actual return value otherwise.
3590 .Ip "shmget(KEY,SIZE,FLAGS)" 8 4
3591 Calls the System V IPC function shmget. Returns the shared memory
3592 segment id, or the undefined value if there is an error.
3593 .Ip "shmread(ID,VAR,POS,SIZE)" 8 4
3594 .Ip "shmwrite(ID,STRING,POS,SIZE)" 8
3595 Reads or writes the System V shared memory segment ID starting at
3596 position POS for size SIZE by attaching to it, copying in/out, and
3597 detaching from it. When reading, VAR must be a variable which
3598 will hold the data read. When writing, if STRING is too long,
3599 only SIZE bytes are used; if STRING is too short, nulls are
3600 written to fill out SIZE bytes. Return true if successful, or
3601 false if there is an error.
3602 .Ip "shutdown(SOCKET,HOW)" 8 3
3603 Shuts down a socket connection in the manner indicated by HOW, which has
3604 the same interpretation as in the system call of the same name.
3607 Returns the sine of EXPR (expressed in radians).
3608 If EXPR is omitted, returns sine of $_.
3609 .Ip "sleep(EXPR)" 8 6
3612 Causes the script to sleep for EXPR seconds, or forever if no EXPR.
3613 May be interrupted by sending the process a SIGALRM.
3614 Returns the number of seconds actually slept.
3615 You probably cannot mix alarm() and sleep() calls, since sleep() is
3616 often implemented using alarm().
3617 .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
3618 Opens a socket of the specified kind and attaches it to filehandle SOCKET.
3619 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
3621 You may need to run h2ph on sys/socket.h to get the proper values handy
3622 in a perl library file.
3623 Return true if successful.
3624 See the example in the section on Interprocess Communication.
3625 .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
3626 Creates an unnamed pair of sockets in the specified domain, of the specified
3628 DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
3630 If unimplemented, yields a fatal error.
3631 Return true if successful.
3632 .Ip "sort(SUBROUTINE LIST)" 8 9
3634 .Ip "sort SUBROUTINE LIST" 8
3635 .Ip "sort BLOCK LIST" 8
3637 Sorts the LIST and returns the sorted array value.
3638 Nonexistent values of arrays are stripped out.
3639 If SUBROUTINE or BLOCK is omitted, sorts in standard string comparison order.
3640 If SUBROUTINE is specified, gives the name of a subroutine that returns
3641 an integer less than, equal to, or greater than 0,
3642 depending on how the elements of the array are to be ordered.
3643 (The <=> and cmp operators are extremely useful in such routines.)
3644 SUBROUTINE may be a scalar variable name, in which case the value provides
3645 the name of the subroutine to use.
3646 In place of a SUBROUTINE name, you can provide a BLOCK as an anonymous,
3647 in-line sort subroutine.
3649 In the interests of efficiency the normal calling code for subroutines
3650 is bypassed, with the following effects: the subroutine may not be a recursive
3651 subroutine, and the two elements to be compared are passed into the subroutine
3652 not via @_ but as $a and $b (see example below).
3653 They are passed by reference so don't modify $a and $b.
3660 @articles = sort @files;
3663 # same thing, but with explicit sort routine
3664 @articles = sort {$a cmp $b;} @files;
3667 # same thing in reversed order
3668 @articles = sort {$b cmp $a;} @files;
3671 # sort numerically ascending
3672 @articles = sort {$a <=> $b;} @files;
3675 # sort numerically descending
3676 @articles = sort {$b <=> $a;} @files;
3679 # sort using explicit subroutine name
3681 $age{$a} <=> $age{$b}; # presuming integers
3683 @sortedclass = sort byage @class;
3686 sub reverse { $b cmp $a; }
3687 @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
3688 @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
3690 # prints AbelCaincatdogx
3691 print sort reverse @harry;
3692 # prints xdogcatCainAbel
3693 print sort @george, \'to\', @harry;
3694 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
3697 .Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
3698 .Ip "splice(ARRAY,OFFSET,LENGTH)" 8
3699 .Ip "splice(ARRAY,OFFSET)" 8
3700 Removes the elements designated by OFFSET and LENGTH from an array, and
3701 replaces them with the elements of LIST, if any.
3702 Returns the elements removed from the array.
3703 The array grows or shrinks as necessary.
3704 If LENGTH is omitted, removes everything from OFFSET onward.
3705 The following equivalencies hold (assuming $[ == 0):
3708 push(@a,$x,$y)\h'|3.5i'splice(@a,$#a+1,0,$x,$y)
3709 pop(@a)\h'|3.5i'splice(@a,-1)
3710 shift(@a)\h'|3.5i'splice(@a,0,1)
3711 unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
3712 $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
3714 Example, assuming array lengths are passed before arrays:
3716 sub aeq { # compare two array values
3717 local(@a) = splice(@_,0,shift);
3718 local(@b) = splice(@_,0,shift);
3719 return 0 unless @a == @b; # same len?
3721 return 0 if pop(@a) ne pop(@b);
3725 if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
3728 .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
3729 .Ip "split(/PATTERN/,EXPR)" 8 8
3730 .Ip "split(/PATTERN/)" 8
3732 Splits a string into an array of strings, and returns it.
3733 (If not in an array context, returns the number of fields found and splits
3735 (In an array context, you can force the split into @_
3736 by using ?? as the pattern delimiters, but it still returns the array value.))
3737 If EXPR is omitted, splits the $_ string.
3738 If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
3739 Anything matching PATTERN is taken to be a delimiter separating the fields.
3740 (Note that the delimiter may be longer than one character.)
3741 If LIMIT is specified, splits into no more than that many fields (though it
3742 may split into fewer).
3743 If LIMIT is unspecified, trailing null fields are stripped (which
3744 potential users of pop() would do well to remember).
3745 A pattern matching the null string (not to be confused with a null pattern //,
3746 which is just one member of the set of patterns matching a null string)
3747 will split the value of EXPR into separate characters at each point it
3752 print join(\':\', split(/ */, \'hi there\'));
3755 produces the output \*(L'h:i:t:h:e:r:e\*(R'.
3757 The LIMIT parameter can be used to partially split a line
3760 ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
3763 (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
3764 larger than the number of variables in the list, to avoid unnecessary work.
3765 For the list above LIMIT would have been 4 by default.
3766 In time critical applications it behooves you not to split into
3767 more fields than you really need.)
3769 If the PATTERN contains parentheses, additional array elements are created
3770 from each matching substring in the delimiter.
3772 split(/([,-])/,"1-10,20");
3774 produces the array value
3778 The pattern /PATTERN/ may be replaced with an expression to specify patterns
3779 that vary at runtime.
3780 (To do runtime compilation only once, use /$variable/o.)
3781 As a special case, specifying a space (\'\ \') will split on white space
3782 just as split with no arguments does, but leading white space does NOT
3783 produce a null first field.
3784 Thus, split(\'\ \') can be used to emulate
3786 default behavior, whereas
3787 split(/\ /) will give you as many null initial fields as there are
3794 open(passwd, \'/etc/passwd\');
3797 ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
3800 ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
3801 = split(\|/\|:\|/\|);
3807 (Note that $shell above will still have a newline on it. See chop().)
3810 .Ip "sprintf(FORMAT,LIST)" 8 4
3811 Returns a string formatted by the usual printf conventions.
3812 The * character is not supported.
3813 .Ip "sqrt(EXPR)" 8 4
3815 Return the square root of EXPR.
3816 If EXPR is omitted, returns square root of $_.
3817 .Ip "srand(EXPR)" 8 4
3819 Sets the random number seed for the
3822 If EXPR is omitted, does srand(time).
3823 .Ip "stat(FILEHANDLE)" 8 8
3824 .Ip "stat FILEHANDLE" 8
3826 .Ip "stat SCALARVARIABLE" 8
3827 Returns a 13-element array giving the statistics for a file, either the file
3828 opened via FILEHANDLE, or named by EXPR.
3829 Typically used as follows:
3833 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
3834 $atime,$mtime,$ctime,$blksize,$blocks)
3838 If stat is passed the special filehandle consisting of an underline,
3839 no stat is done, but the current contents of the stat structure from
3840 the last stat or filetest are returned.
3845 if (-x $file && (($d) = stat(_)) && $d < 0) {
3846 print "$file is executable NFS file\en";
3850 (This only works on machines for which the device number is negative under NFS.)
3851 .Ip "study(SCALAR)" 8 6
3852 .Ip "study SCALAR" 8
3854 Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
3855 doing many pattern matches on the string before it is next modified.
3856 This may or may not save time, depending on the nature and number of patterns
3857 you are searching on, and on the distribution of character frequencies in
3858 the string to be searched\*(--you probably want to compare runtimes with and
3859 without it to see which runs faster.
3860 Those loops which scan for many short constant strings (including the constant
3861 parts of more complex patterns) will benefit most.
3862 You may have only one study active at a time\*(--if you study a different
3863 scalar the first is \*(L"unstudied\*(R".
3864 (The way study works is this: a linked list of every character in the string
3865 to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
3867 From each search string, the rarest character is selected, based on some
3868 static frequency tables constructed from some C programs and English text.
3869 Only those places that contain this \*(L"rarest\*(R" character are examined.)
3871 For example, here is a loop which inserts index producing entries before any line
3872 containing a certain pattern:
3878 print ".IX foo\en" if /\ebfoo\eb/;
3879 print ".IX bar\en" if /\ebbar\eb/;
3880 print ".IX blurfl\en" if /\ebblurfl\eb/;
3886 In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
3887 will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
3888 In general, this is a big win except in pathological cases.
3889 The only question is whether it saves you more time than it took to build
3890 the linked list in the first place.
3892 Note that if you have to look for strings that you don't know till runtime,
3893 you can build an entire loop as a string and eval that to avoid recompiling
3894 all your patterns all the time.
3895 Together with undefining $/ to input entire files as one record, this can
3896 be very fast, often faster than specialized programs like fgrep.
3897 The following scans a list of files (@files)
3898 for a list of words (@words), and prints out the names of those files that
3903 $search = \'while (<>) { study;\';
3904 foreach $word (@words) {
3905 $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
3910 eval $search; # this screams
3911 $/ = "\en"; # put back to normal input delim
3912 foreach $file (sort keys(%seen)) {
3917 .Ip "substr(EXPR,OFFSET,LEN)" 8 2
3918 .Ip "substr(EXPR,OFFSET)" 8 2
3919 Extracts a substring out of EXPR and returns it.
3920 First character is at offset 0, or whatever you've set $[ to.
3921 If OFFSET is negative, starts that far from the end of the string.
3922 If LEN is omitted, returns everything to the end of the string.
3923 You can use the substr() function as an lvalue, in which case EXPR must
3925 If you assign something shorter than LEN, the string will shrink, and
3926 if you assign something longer than LEN, the string will grow to accommodate it.
3927 To keep the string the same length you may need to pad or chop your value using
3929 .Ip "symlink(OLDFILE,NEWFILE)" 8 2
3930 Creates a new filename symbolically linked to the old filename.
3931 Returns 1 for success, 0 otherwise.
3932 On systems that don't support symbolic links, produces a fatal error at
3934 To check for that, use eval:
3937 $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
3940 .Ip "syscall(LIST)" 8 6
3941 .Ip "syscall LIST" 8
3942 Calls the system call specified as the first element of the list, passing
3943 the remaining elements as arguments to the system call.
3944 If unimplemented, produces a fatal error.
3945 The arguments are interpreted as follows: if a given argument is numeric,
3946 the argument is passed as an int.
3947 If not, the pointer to the string value is passed.
3948 You are responsible to make sure a string is pre-extended long enough
3949 to receive any result that might be written into a string.
3950 If your integer arguments are not literals and have never been interpreted
3951 in a numeric context, you may need to add 0 to them to force them to look
3955 require 'syscall.ph'; # may need to run h2ph
3956 syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
3959 .Ip "sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
3960 .Ip "sysread(FILEHANDLE,SCALAR,LENGTH)" 8 5
3961 Attempts to read LENGTH bytes of data into variable SCALAR from the specified
3962 FILEHANDLE, using the system call read(2).
3963 It bypasses stdio, so mixing this with other kinds of reads may cause
3965 Returns the number of bytes actually read, or undef if there was an error.
3966 SCALAR will be grown or shrunk to the length actually read.
3967 An OFFSET may be specified to place the read data at some other place
3968 than the beginning of the string.
3969 .Ip "system(LIST)" 8 6
3971 Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
3972 is done first, and the parent process waits for the child process to complete.
3973 Note that argument processing varies depending on the number of arguments.
3974 The return value is the exit status of the program as returned by the wait()
3976 To get the actual exit value divide by 256.
3979 .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
3980 .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH)" 8 5
3981 Attempts to write LENGTH bytes of data from variable SCALAR to the specified
3982 FILEHANDLE, using the system call write(2).
3983 It bypasses stdio, so mixing this with prints may cause
3985 Returns the number of bytes actually written, or undef if there was an error.
3986 An OFFSET may be specified to place the read data at some other place
3987 than the beginning of the string.
3988 .Ip "tell(FILEHANDLE)" 8 6
3989 .Ip "tell FILEHANDLE" 8 6
3991 Returns the current file position for FILEHANDLE.
3992 FILEHANDLE may be an expression whose value gives the name of the actual
3994 If FILEHANDLE is omitted, assumes the file last read.
3995 .Ip "telldir(DIRHANDLE)" 8 5
3996 .Ip "telldir DIRHANDLE" 8
3997 Returns the current position of the readdir() routines on DIRHANDLE.
3998 Value may be given to seekdir() to access a particular location in
4000 Has the same caveats about possible directory compaction as the corresponding
4001 system library routine.
4003 Returns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970.
4004 Suitable for feeding to gmtime() and localtime().
4006 Returns a four-element array giving the user and system times, in seconds, for this
4007 process and the children of this process.
4009 ($user,$system,$cuser,$csystem) = times;
4011 .Ip "tr/SEARCHLIST/REPLACEMENTLIST/cds" 8 5
4012 .Ip "y/SEARCHLIST/REPLACEMENTLIST/cds" 8
4013 Translates all occurrences of the characters found in the search list with
4014 the corresponding character in the replacement list.
4015 It returns the number of characters replaced or deleted.
4016 If no string is specified via the =~ or !~ operator,
4017 the $_ string is translated.
4018 (The string specified with =~ must be a scalar variable, an array element,
4019 or an assignment to one of those, i.e. an lvalue.)
4024 is provided as a synonym for
4027 If the c modifier is specified, the SEARCHLIST character set is complemented.
4028 If the d modifier is specified, any characters specified by SEARCHLIST that
4029 are not found in REPLACEMENTLIST are deleted.
4030 (Note that this is slightly more flexible than the behavior of some
4032 programs, which delete anything they find in the SEARCHLIST, period.)
4033 If the s modifier is specified, sequences of characters that were translated
4034 to the same character are squashed down to 1 instance of the character.
4036 If the d modifier was used, the REPLACEMENTLIST is always interpreted exactly
4038 Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST,
4039 the final character is replicated till it is long enough.
4040 If the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
4041 This latter is useful for counting characters in a class, or for squashing
4042 character sequences in a class.
4047 $ARGV[1] \|=~ \|y/A\-Z/a\-z/; \h'|3i'# canonicalize to lower case
4049 $cnt = tr/*/*/; \h'|3i'# count the stars in $_
4051 $cnt = tr/0\-9//; \h'|3i'# count the digits in $_
4053 tr/a\-zA\-Z//s; \h'|3i'# bookkeeper \-> bokeper
4055 ($HOST = $host) =~ tr/a\-z/A\-Z/;
4057 y/a\-zA\-Z/ /cs; \h'|3i'# change non-alphas to single space
4059 tr/\e200\-\e377/\e0\-\e177/;\h'|3i'# delete 8th bit
4062 .Ip "truncate(FILEHANDLE,LENGTH)" 8 4
4063 .Ip "truncate(EXPR,LENGTH)" 8
4064 Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified
4066 Produces a fatal error if truncate isn't implemented on your system.
4067 .Ip "umask(EXPR)" 8 4
4070 Sets the umask for the process and returns the old one.
4071 If EXPR is omitted, merely returns current umask.
4072 .Ip "undef(EXPR)" 8 6
4075 Undefines the value of EXPR, which must be an lvalue.
4076 Use only on a scalar value, an entire array, or a subroutine name (using &).
4077 (Undef will probably not do what you expect on most predefined variables or
4079 Always returns the undefined value.
4080 You can omit the EXPR, in which case nothing is undefined, but you still
4081 get an undefined value that you could, for instance, return from a subroutine.
4087 undef $bar{'blurfl'};
4091 return (wantarray ? () : undef) if $they_blew_it;
4094 .Ip "unlink(LIST)" 8 4
4096 Deletes a list of files.
4097 Returns the number of files successfully deleted.
4101 $cnt = unlink \'a\', \'b\', \'c\';
4106 Note: unlink will not delete directories unless you are superuser and the
4110 Even if these conditions are met, be warned that unlinking a directory
4111 can inflict damage on your filesystem.
4113 .Ip "unpack(TEMPLATE,EXPR)" 8 4
4114 Unpack does the reverse of pack: it takes a string representing
4115 a structure and expands it out into an array value, returning the array
4117 (In a scalar context, it merely returns the first value produced.)
4118 The TEMPLATE has the same format as in the pack function.
4119 Here's a subroutine that does substring:
4124 local($what,$where,$howmuch) = @_;
4125 unpack("x$where a$howmuch", $what);
4131 sub ord { unpack("c",$_[0]); }
4134 In addition, you may prefix a field with a %<number> to indicate that
4135 you want a <number>-bit checksum of the items instead of the items themselves.
4136 Default is a 16-bit checksum.
4137 For example, the following computes the same number as the System V sum program:
4142 $checksum += unpack("%16C*", $_);
4147 .Ip "unshift(ARRAY,LIST)" 8 4
4148 Does the opposite of a
4150 Or the opposite of a
4152 depending on how you look at it.
4153 Prepends list to the front of the array, and returns the number of elements
4157 unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
4160 .Ip "utime(LIST)" 8 2
4161 .Ip "utime LIST" 8 2
4162 Changes the access and modification times on each file of a list of files.
4163 The first two elements of the list must be the NUMERICAL access and
4164 modification times, in that order.
4165 Returns the number of files successfully changed.
4166 The inode modification time of each file is set to the current time.
4167 Example of a \*(L"touch\*(R" command:
4173 utime $now, $now, @ARGV;
4176 .Ip "values(ASSOC_ARRAY)" 8 6
4177 .Ip "values ASSOC_ARRAY" 8
4178 Returns a normal array consisting of all the values of the named associative
4180 The values are returned in an apparently random order, but it is the same order
4181 as either the keys() or each() function would produce on the same array.
4182 See also keys() and each().
4183 .Ip "vec(EXPR,OFFSET,BITS)" 8 2
4184 Treats a string as a vector of unsigned integers, and returns the value
4185 of the bitfield specified.
4186 May also be assigned to.
4187 BITS must be a power of two from 1 to 32.
4189 Vectors created with vec() can also be manipulated with the logical operators
4191 which will assume a bit vector operation is desired when both operands are
4193 This interpretation is not enabled unless there is at least one vec() in
4194 your program, to protect older programs.
4196 To transform a bit vector into a string or array of 0's and 1's, use these:
4199 $bits = unpack("b*", $vector);
4200 @bits = split(//, unpack("b*", $vector));
4203 If you know the exact length in bits, it can be used in place of the *.
4205 Waits for a child process to terminate and returns the pid of the deceased
4206 process, or -1 if there are no child processes.
4207 The status is returned in $?.
4208 .Ip "waitpid(PID,FLAGS)" 8 6
4209 Waits for a particular child process to terminate and returns the pid of the deceased
4210 process, or -1 if there is no such child process.
4211 The status is returned in $?.
4215 require "sys/wait.h";
4217 waitpid(-1,&WNOHANG);
4220 then you can do a non-blocking wait for any process. Non-blocking wait
4221 is only available on machines supporting either the
4226 However, waiting for a particular pid with FLAGS of 0 is implemented
4227 everywhere. (Perl emulates the system call by remembering the status
4228 values of processes that have exited but have not been harvested by the
4231 Returns true if the context of the currently executing subroutine
4232 is looking for an array value.
4233 Returns false if the context is looking for a scalar.
4236 return wantarray ? () : undef;
4239 .Ip "warn(LIST)" 8 4
4241 Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
4242 .Ip "write(FILEHANDLE)" 8 6
4245 Writes a formatted record (possibly multi-line) to the specified file,
4246 using the format associated with that file.
4247 By default the format for a file is the one having the same name is the
4248 filehandle, but the format for the current output channel (see
4250 may be set explicitly
4251 by assigning the name of the format to the $~ variable.
4253 Top of form processing is handled automatically:
4254 if there is insufficient room on the current page for the formatted
4255 record, the page is advanced by writing a form feed,
4256 a special top-of-page format is used
4257 to format the new page header, and then the record is written.
4258 By default the top-of-page format is the name of the filehandle with
4259 \*(L"_TOP\*(R" appended, but it may be dynamicallly set to the
4260 format of your choice by assigning the name to the $^ variable while
4261 the filehandle is selected.
4262 The number of lines remaining on the current page is in variable $-, which
4263 can be set to 0 to force a new page.
4265 If FILEHANDLE is unspecified, output goes to the current default output channel,
4268 but may be changed by the
4271 If the FILEHANDLE is an EXPR, then the expression is evaluated and the
4272 resulting string is used to look up the name of the FILEHANDLE at run time.
4273 For more on formats, see the section on formats later on.
4275 Note that write is NOT the opposite of read.
4278 operators have the following associativity and precedence:
4281 nonassoc\h'|1i'print printf exec system sort reverse
4282 \h'1.5i'chmod chown kill unlink utime die return
4284 right\h'|1i'= += \-= *= etc.
4291 nonassoc\h'|1i'== != <=> eq ne cmp
4292 nonassoc\h'|1i'< > <= >= lt gt le ge
4293 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
4294 nonassoc\h'|1i'\-r \-w \-x etc.
4299 right\h'|1i'! ~ and unary minus
4301 nonassoc\h'|1i'++ \-\|\-
4302 left\h'|1i'\*(L'(\*(R'
4305 As mentioned earlier, if any list operator (print, etc.) or
4306 any unary operator (chdir, etc.)
4307 is followed by a left parenthesis as the next token on the same line,
4308 the operator and arguments within parentheses are taken to
4309 be of highest precedence, just like a normal function call.
4313 chdir $foo || die;\h'|3i'# (chdir $foo) || die
4314 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
4315 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
4316 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
4318 but, because * is higher precedence than ||:
4320 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
4321 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
4322 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
4323 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
4325 rand 10 * 20;\h'|3i'# rand (10 * 20)
4326 rand(10) * 20;\h'|3i'# (rand 10) * 20
4327 rand (10) * 20;\h'|3i'# (rand 10) * 20
4328 rand +(10) * 20;\h'|3i'# rand (10 * 20)
4331 In the absence of parentheses,
4332 the precedence of list operators such as print, sort or chmod is
4333 either very high or very low depending on whether you look at the left
4334 side of operator or the right side of it.
4338 @ary = (1, 3, sort 4, 2);
4339 print @ary; # prints 1324
4342 the commas on the right of the sort are evaluated before the sort, but
4343 the commas on the left are evaluated after.
4344 In other words, list operators tend to gobble up all the arguments that
4345 follow them, and then act like a simple term with regard to the preceding
4347 Note that you have to be careful with parens:
4351 # These evaluate exit before doing the print:
4352 print($foo, exit); # Obviously not what you want.
4353 print $foo, exit; # Nor is this.
4356 # These do the print before evaluating exit:
4357 (print $foo), exit; # This is what you want.
4358 print($foo), exit; # Or this.
4359 print ($foo), exit; # Or even this.
4363 print ($foo & 255) + 1, "\en";
4366 probably doesn't do what you expect at first glance.
4368 A subroutine may be declared as follows:
4375 Any arguments passed to the routine come in as array @_,
4376 that is ($_[0], $_[1], .\|.\|.).
4377 The array @_ is a local array, but its values are references to the
4378 actual scalar parameters.
4379 The return value of the subroutine is the value of the last expression
4380 evaluated, and can be either an array value or a scalar value.
4381 Alternately, a return statement may be used to specify the returned value and
4382 exit the subroutine.
4383 To create local variables see the
4387 A subroutine is called using the
4389 operator or the & operator.
4396 local($max) = pop(@_);
4398 $max = $foo \|if \|$max < $foo;
4404 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
4409 # get a line, combining continuation lines
4410 # that start with whitespace
4412 $thisline = $lookahead;
4413 line: while ($lookahead = <STDIN>) {
4414 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
4415 $thisline \|.= \|$lookahead;
4424 $lookahead = <STDIN>; # get first line
4425 while ($_ = do get_line(\|)) {
4432 Use array assignment to a local list to name your formal arguments:
4435 local($key, $value) = @_;
4436 $foo{$key} = $value unless $foo{$key};
4440 This also has the effect of turning call-by-reference into call-by-value,
4441 since the assignment copies the values.
4443 Subroutines may be called recursively.
4444 If a subroutine is called using the & form, the argument list is optional.
4445 If omitted, no @_ array is set up for the subroutine; the @_ array at the
4446 time of the call is visible to subroutine instead.
4449 do foo(1,2,3); # pass three arguments
4450 &foo(1,2,3); # the same
4452 do foo(); # pass a null list
4454 &foo; # pass no arguments\*(--more efficient
4457 .Sh "Passing By Reference"
4458 Sometimes you don't want to pass the value of an array to a subroutine but
4459 rather the name of it, so that the subroutine can modify the global copy
4460 of it rather than working with a local copy.
4461 In perl you can refer to all the objects of a particular name by prefixing
4462 the name with a star: *foo.
4463 When evaluated, it produces a scalar value that represents all the objects
4464 of that name, including any filehandle, format or subroutine.
4465 When assigned to within a local() operation, it causes the name mentioned
4466 to refer to whatever * value was assigned to it.
4471 local(*someary) = @_;
4472 foreach $elem (@someary) {
4480 Assignment to *name is currently recommended only inside a local().
4481 You can actually assign to *name anywhere, but the previous referent of
4482 *name may be stranded forever.
4483 This may or may not bother you.
4485 Note that scalars are already passed by reference, so you can modify scalar
4486 arguments without using this mechanism by referring explicitly to the $_[nnn]
4488 You can modify all the elements of an array by passing all the elements
4489 as scalars, but you have to use the * mechanism to push, pop or change the
4491 The * mechanism will probably be more efficient in any case.
4493 Since a *name value contains unprintable binary data, if it is used as
4494 an argument in a print, or as a %s argument in a printf or sprintf, it
4495 then has the value '*name', just so it prints out pretty.
4497 Even if you don't want to modify an array, this mechanism is useful for
4498 passing multiple arrays in a single LIST, since normally the LIST mechanism
4499 will merge all the array values so that you can't extract out the
4501 .Sh "Regular Expressions"
4502 The patterns used in pattern matching are regular expressions such as
4503 those supplied in the Version 8 regexp routines.
4504 (In fact, the routines are derived from Henry Spencer's freely redistributable
4505 reimplementation of the V8 routines.)
4506 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
4507 Word boundaries may be matched by \eb, and non-boundaries by \eB.
4508 A whitespace character is matched by \es, non-whitespace by \eS.
4509 A numeric character is matched by \ed, non-numeric by \eD.
4510 You may use \ew, \es and \ed within character classes.
4511 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
4512 Within character classes \eb represents backspace rather than a word boundary.
4513 Alternatives may be separated by |.
4514 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
4515 matches the digit'th substring.
4516 (Outside of the pattern, always use $ instead of \e in front of the digit.
4517 The scope of $<digit> (and $\`, $& and $\')
4518 extends to the end of the enclosing BLOCK or eval string, or to
4519 the next pattern match with subexpressions.
4520 The \e<digit> notation sometimes works outside the current pattern, but should
4521 not be relied upon.)
4522 You may have as many parentheses as you wish. If you have more than 9
4523 substrings, the variables $10, $11, ... refer to the corresponding
4524 substring. Within the pattern, \e10, \e11,
4525 etc. refer back to substrings if there have been at least that many left parens
4526 before the backreference. Otherwise (for backward compatibilty) \e10
4527 is the same as \e010, a backspace,
4528 and \e11 the same as \e011, a tab.
4530 (\e1 through \e9 are always backreferences.)
4532 $+ returns whatever the last bracket match matched.
4533 $& returns the entire matched string.
4534 ($0 used to return the same thing, but not any more.)
4535 $\` returns everything before the matched string.
4536 $\' returns everything after the matched string.
4540 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
4543 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
4550 By default, the ^ character is only guaranteed to match at the beginning
4552 the $ character only at the end (or before the newline at the end)
4555 does certain optimizations with the assumption that the string contains
4557 The behavior of ^ and $ on embedded newlines will be inconsistent.
4558 You may, however, wish to treat a string as a multi-line buffer, such that
4559 the ^ will match after any newline within the string, and $ will match
4561 At the cost of a little more overhead, you can do this by setting the variable
4563 Setting it back to 0 makes
4565 revert to its old behavior.
4567 To facilitate multi-line substitutions, the . character never matches a newline
4568 (even when $* is 0).
4569 In particular, the following leaves a newline on the $_ string:
4573 s/.*(some_string).*/$1/;
4575 If the newline is unwanted, try one of
4577 s/.*(some_string).*\en/$1/;
4578 s/.*(some_string)[^\e000]*/$1/;
4579 s/.*(some_string)(.|\en)*/$1/;
4580 chop; s/.*(some_string).*/$1/;
4581 /(some_string)/ && ($_ = $1);
4584 Any item of a regular expression may be followed with digits in curly brackets
4585 of the form {n,m}, where n gives the minimum number of times to match the item
4586 and m gives the maximum.
4587 The form {n} is equivalent to {n,n} and matches exactly n times.
4588 The form {n,} matches n or more times.
4589 (If a curly bracket occurs in any other context, it is treated as a regular
4591 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
4593 There is no limit to the size of n or m, but large numbers will chew up
4596 You will note that all backslashed metacharacters in
4599 such as \eb, \ew, \en.
4600 Unlike some other regular expression languages, there are no backslashed
4601 symbols that aren't alphanumeric.
4602 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
4603 interpreted as a literal character, not a metacharacter.
4604 This makes it simple to quote a string that you want to use for a pattern
4605 but that you are afraid might contain metacharacters.
4606 Simply quote all the non-alphanumeric characters:
4609 $pattern =~ s/(\eW)/\e\e$1/g;
4613 Output record formats for use with the
4615 operator may declared as follows:
4624 If name is omitted, format \*(L"STDOUT\*(R" is defined.
4625 FORMLIST consists of a sequence of lines, each of which may be of one of three
4630 A \*(L"picture\*(R" line giving the format for one output line.
4632 An argument line supplying values to plug into a picture line.
4634 Picture lines are printed exactly as they look, except for certain fields
4635 that substitute values into the line.
4636 Each picture field starts with either @ or ^.
4637 The @ field (not to be confused with the array marker @) is the normal
4638 case; ^ fields are used
4639 to do rudimentary multi-line text block filling.
4640 The length of the field is supplied by padding out the field
4641 with multiple <, >, or | characters to specify, respectively, left justification,
4642 right justification, or centering.
4643 As an alternate form of right justification,
4644 you may also use # characters (with an optional .) to specify a numeric field.
4645 (Use of ^ instead of @ causes the field to be blanked if undefined.)
4646 If any of the values supplied for these fields contains a newline, only
4647 the text up to the newline is printed.
4648 The special field @* can be used for printing multi-line values.
4649 It should appear by itself on a line.
4651 The values are specified on the following line, in the same order as
4653 The values should be separated by commas.
4655 Picture fields that begin with ^ rather than @ are treated specially.
4656 The value supplied must be a scalar variable name which contains a text
4659 puts as much text as it can into the field, and then chops off the front
4660 of the string so that the next time the variable is referenced,
4661 more of the text can be printed.
4662 Normally you would use a sequence of fields in a vertical stack to print
4663 out a block of text.
4664 If you like, you can end the final field with .\|.\|., which will appear in the
4665 output if the text was too long to appear in its entirety.
4666 You can change which characters are legal to break on by changing the
4667 variable $: to a list of the desired characters.
4669 Since use of ^ fields can produce variable length records if the text to be
4670 formatted is short, you can suppress blank lines by putting the tilde (~)
4671 character anywhere in the line.
4672 (Normally you should put it in the front if possible, for visibility.)
4673 The tilde will be translated to a space upon output.
4674 If you put a second tilde contiguous to the first, the line will be repeated
4675 until all the fields on the line are exhausted.
4676 (If you use a field of the @ variety, the expression you supply had better
4677 not give the same value every time forever!)
4686 # a report on the /etc/passwd file
4689 Name Login Office Uid Gid Home
4690 ------------------------------------------------------------------
4693 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
4694 $name, $login, $office,$uid,$gid, $home
4698 # a report from a bug report form
4701 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
4703 ------------------------------------------------------------------
4706 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4708 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4709 \& $index, $description
4710 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4711 \& $priority, $date, $description
4712 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4713 \& $from, $description
4714 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4715 \& $programmer, $description
4716 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4718 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4720 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4722 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4724 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
4732 It is possible to intermix prints with writes on the same output channel,
4733 but you'll have to handle $\- (lines left on the page) yourself.
4735 If you are printing lots of fields that are usually blank, you should consider
4736 using the reset operator between records.
4737 Not only is it more efficient, but it can prevent the bug of adding another
4738 field and forgetting to zero it.
4739 .Sh "Interprocess Communication"
4740 The IPC facilities of perl are built on the Berkeley socket mechanism.
4741 If you don't have sockets, you can ignore this section.
4742 The calls have the same names as the corresponding system calls,
4743 but the arguments tend to differ, for two reasons.
4744 First, perl file handles work differently than C file descriptors.
4745 Second, perl already knows the length of its strings, so you don't need
4746 to pass that information.
4747 Here is a sample client (untested):
4750 ($them,$port) = @ARGV;
4751 $port = 2345 unless $port;
4752 $them = 'localhost' unless $them;
4754 $SIG{'INT'} = 'dokill';
4755 sub dokill { kill 9,$child if $child; }
4757 require 'sys/socket.ph';
4759 $sockaddr = 'S n a4 x8';
4760 chop($hostname = `hostname`);
4762 ($name, $aliases, $proto) = getprotobyname('tcp');
4763 ($name, $aliases, $port) = getservbyname($port, 'tcp')
4764 unless $port =~ /^\ed+$/;
4766 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
4769 ($name, $aliases, $type, $len, $thisaddr) =
4770 gethostbyname($hostname);
4772 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
4774 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
4775 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
4777 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
4778 bind(S, $this) || die "bind: $!";
4779 connect(S, $that) || die "connect: $!";
4781 select(S); $| = 1; select(stdout);
4783 if ($child = fork) {
4797 And here's a server:
4801 $port = 2345 unless $port;
4803 require 'sys/socket.ph';
4805 $sockaddr = 'S n a4 x8';
4807 ($name, $aliases, $proto) = getprotobyname('tcp');
4808 ($name, $aliases, $port) = getservbyname($port, 'tcp')
4809 unless $port =~ /^\ed+$/;
4811 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
4813 select(NS); $| = 1; select(stdout);
4815 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
4816 bind(S, $this) || die "bind: $!";
4817 listen(S, 5) || die "connect: $!";
4819 select(S); $| = 1; select(stdout);
4822 print "Listening again\en";
4823 ($addr = accept(NS,S)) || die $!;
4824 print "accept ok\en";
4826 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
4827 @inetaddr = unpack('C4',$inetaddr);
4828 print "$af $port @inetaddr\en";
4837 .Sh "Predefined Names"
4838 The following names have special meaning to
4840 I could have used alphabetic symbols for some of these, but I didn't want
4841 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
4843 You'll just have to suffer along with these silly symbols.
4844 Most of them have reasonable mnemonics, or analogues in one of the shells.
4846 The default input and pattern-searching space.
4847 The following pairs are equivalent:
4851 while (<>) {\|.\|.\|. # only equivalent in while!
4852 while ($_ = <>) {\|.\|.\|.
4856 $_ \|=~ \|/\|^Subject:/
4867 (Mnemonic: underline is understood in certain operations.)
4869 The current input line number of the last filehandle that was read.
4871 Remember that only an explicit close on the filehandle resets the line number.
4872 Since <> never does an explicit close, line numbers increase across ARGV files
4873 (but see examples under eof).
4874 (Mnemonic: many programs use . to mean the current line number.)
4876 The input record separator, newline by default.
4879 RS variable, including treating blank lines as delimiters
4880 if set to the null string.
4881 You may set it to a multicharacter string to match a multi-character
4883 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
4885 The output field separator for the print operator.
4886 Ordinarily the print operator simply prints out the comma separated fields
4888 In order to get behavior more like
4890 set this variable as you would set
4892 OFS variable to specify what is printed between fields.
4893 (Mnemonic: what is printed when there is a , in your print statement.)
4895 This is like $, except that it applies to array values interpolated into
4896 a double-quoted string (or similar interpreted string).
4898 (Mnemonic: obvious, I think.)
4900 The output record separator for the print operator.
4901 Ordinarily the print operator simply prints out the comma separated fields
4902 you specify, with no trailing newline or record separator assumed.
4903 In order to get behavior more like
4905 set this variable as you would set
4907 ORS variable to specify what is printed at the end of the print.
4908 (Mnemonic: you set $\e instead of adding \en at the end of the print.
4909 Also, it's just like /, but it's what you get \*(L"back\*(R" from
4912 The output format for printed numbers.
4913 This variable is a half-hearted attempt to emulate
4916 There are times, however, when
4920 have differing notions of what
4922 Also, the initial value is %.20g rather than %.6g, so you need to set $#
4926 (Mnemonic: # is the number sign.)
4928 The current page number of the currently selected output channel.
4929 (Mnemonic: % is page number in nroff.)
4931 The current page length (printable lines) of the currently selected output
4934 (Mnemonic: = has horizontal lines.)
4936 The number of lines left on the page of the currently selected output channel.
4937 (Mnemonic: lines_on_page \- lines_printed.)
4939 The name of the current report format for the currently selected output
4941 Default is name of the filehandle.
4942 (Mnemonic: brother to $^.)
4944 The name of the current top-of-page format for the currently selected output
4946 Default is name of the filehandle with \*(L"_TOP\*(R" appended.
4947 (Mnemonic: points to top of page.)
4949 If set to nonzero, forces a flush after every write or print on the currently
4950 selected output channel.
4954 will typically be line buffered if output is to the
4955 terminal and block buffered otherwise.
4956 Setting this variable is useful primarily when you are outputting to a pipe,
4957 such as when you are running a
4959 script under rsh and want to see the
4960 output as it's happening.
4961 (Mnemonic: when you want your pipes to be piping hot.)
4963 The process number of the
4965 running this script.
4966 (Mnemonic: same as shells.)
4968 The status returned by the last pipe close, backtick (\`\`) command or
4971 Note that this is the status word returned by the wait() system
4972 call, so the exit value of the subprocess is actually ($? >> 8).
4973 $? & 255 gives which signal, if any, the process died from, and whether
4974 there was a core dump.
4975 (Mnemonic: similar to sh and ksh.)
4977 The string matched by the last pattern match (not counting any matches hidden
4978 within a BLOCK or eval enclosed by the current BLOCK).
4979 (Mnemonic: like & in some editors.)
4981 The string preceding whatever was matched by the last pattern match
4982 (not counting any matches hidden within a BLOCK or eval enclosed by the current
4984 (Mnemonic: \` often precedes a quoted string.)
4986 The string following whatever was matched by the last pattern match
4987 (not counting any matches hidden within a BLOCK or eval enclosed by the current
4989 (Mnemonic: \' often follows a quoted string.)
4996 print "$\`:$&:$\'\en"; # prints abc:def:ghi
5000 The last bracket matched by the last search pattern.
5001 This is useful if you don't know which of a set of alternative patterns
5006 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
5009 (Mnemonic: be positive and forward looking.)
5011 Set to 1 to do multiline matching within a string, 0 to tell
5013 that it can assume that strings contain a single line, for the purpose
5014 of optimizing pattern matches.
5015 Pattern matches on strings containing multiple newlines can produce confusing
5016 results when $* is 0.
5018 (Mnemonic: * matches multiple things.)
5019 Note that this variable only influences the interpretation of ^ and $.
5020 A literal newline can be searched for even when $* == 0.
5022 Contains the name of the file containing the
5024 script being executed.
5025 Assigning to $0 modifies the argument area that the ps(1) program sees.
5026 (Mnemonic: same as sh and ksh.)
5028 Contains the subpattern from the corresponding set of parentheses in the last
5029 pattern matched, not counting patterns matched in nested blocks that have
5030 been exited already.
5031 (Mnemonic: like \edigit.)
5033 The index of the first element in an array, and of the first character in
5035 Default is 0, but you could set it to 1 to make
5040 when subscripting and when evaluating the index() and substr() functions.
5041 (Mnemonic: [ begins subscripts.)
5043 The string printed out when you say \*(L"perl -v\*(R".
5044 It can be used to determine at the beginning of a script whether the perl
5045 interpreter executing the script is in the right range of versions.
5046 If used in a numeric context, returns the version + patchlevel / 1000.
5051 # see if getc is available
5052 ($version,$patchlevel) =
5053 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
5054 print STDERR "(No filename completion available.)\en"
5055 if $version * 1000 + $patchlevel < 2016;
5057 or, used numerically,
5059 warn "No checksumming!\en" if $] < 3.019;
5062 (Mnemonic: Is this version of perl in the right bracket?)
5064 The subscript separator for multi-dimensional array emulation.
5065 If you refer to an associative array element as
5071 $foo{join($;, $a, $b, $c)}
5075 @foo{$a,$b,$c} # a slice\*(--note the @
5079 ($foo{$a},$foo{$b},$foo{$c})
5082 Default is "\e034", the same as SUBSEP in
5084 Note that if your keys contain binary data there might not be any safe
5086 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
5087 Yeah, I know, it's pretty lame, but $, is already taken for something more
5090 If used in a numeric context, yields the current value of errno, with all the
5092 (This means that you shouldn't depend on the value of $! to be anything
5093 in particular unless you've gotten a specific error return indicating a
5095 If used in a string context, yields the corresponding system error string.
5096 You can assign to $! in order to set errno
5097 if, for instance, you want $! to return the string for error n, or you want
5098 to set the exit value for the die operator.
5099 (Mnemonic: What just went bang?)
5101 The perl syntax error message from the last eval command.
5102 If null, the last eval parsed and executed correctly (although the operations
5103 you invoked may have failed in the normal fashion).
5104 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
5106 The real uid of this process.
5107 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
5109 The effective uid of this process.
5114 $< = $>; # set real uid to the effective uid
5115 ($<,$>) = ($>,$<); # swap real and effective uid
5118 (Mnemonic: it's the uid you went TO, if you're running setuid.)
5119 Note: $< and $> can only be swapped on machines supporting setreuid().
5121 The real gid of this process.
5122 If you are on a machine that supports membership in multiple groups
5123 simultaneously, gives a space separated list of groups you are in.
5124 The first number is the one returned by getgid(), and the subsequent ones
5125 by getgroups(), one of which may be the same as the first number.
5126 (Mnemonic: parentheses are used to GROUP things.
5127 The real gid is the group you LEFT, if you're running setgid.)
5129 The effective gid of this process.
5130 If you are on a machine that supports membership in multiple groups
5131 simultaneously, gives a space separated list of groups you are in.
5132 The first number is the one returned by getegid(), and the subsequent ones
5133 by getgroups(), one of which may be the same as the first number.
5134 (Mnemonic: parentheses are used to GROUP things.
5135 The effective gid is the group that's RIGHT for you, if you're running setgid.)
5137 Note: $<, $>, $( and $) can only be set on machines that support the
5138 corresponding set[re][ug]id() routine.
5139 $( and $) can only be swapped on machines supporting setregid().
5141 The current set of characters after which a string may be broken to
5142 fill continuation fields (starting with ^) in a format.
5143 Default is "\ \en-", to break on whitespace or hyphens.
5144 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
5146 The current value of the debugging flags.
5151 The maximum system file descriptor, ordinarily 2. System file descriptors
5152 are passed to subprocesses, while higher file descriptors are not.
5153 During an open, system file descriptors are preserved even if the open
5154 fails. Ordinary file descriptors are closed before the open is attempted.
5156 The current value of the inplace-edit extension.
5157 Use undef to disable inplace editing.
5162 The internal flag that the debugger clears so that it doesn't
5163 debug itself. You could conceivable disable debugging yourself
5166 The time at which the script began running, in seconds since the epoch.
5167 The values returned by the
5172 filetests are based on this value.
5174 The current value of the warning switch.
5175 (Mnemonic: related to the
5179 The name that Perl itself was executed as, from argv[0].
5181 contains the name of the current file when reading from <>.
5183 The array ARGV contains the command line arguments intended for the script.
5184 Note that $#ARGV is the generally number of arguments minus one, since
5185 $ARGV[0] is the first argument, NOT the command name.
5186 See $0 for the command name.
5188 The array INC contains the list of places to look for
5191 evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(R" command.
5192 It initially consists of the arguments to any
5194 command line switches, followed
5197 library, probably \*(L"/usr/local/lib/perl\*(R",
5198 followed by \*(L".\*(R", to represent the current directory.
5200 The associative array INC contains entries for each filename that has
5201 been included via \*(L"do\*(R" or \*(L"require\*(R".
5202 The key is the filename you specified, and the value is the location of
5203 the file actually found.
5204 The \*(L"require\*(R" command uses this array to determine whether
5205 a given file has already been included.
5207 The associative array ENV contains your current environment.
5208 Setting a value in ENV changes the environment for child processes.
5210 The associative array SIG is used to set signal handlers for various signals.
5215 sub handler { # 1st argument is signal name
5217 print "Caught a SIG$sig\-\|\-shutting down\en";
5222 $SIG{\'INT\'} = \'handler\';
5223 $SIG{\'QUIT\'} = \'handler\';
5225 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
5226 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
5229 The SIG array only contains values for the signals actually set within
5232 Perl provides a mechanism for alternate namespaces to protect packages from
5233 stomping on each others variables.
5234 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
5237 declaration, you can switch namespaces.
5238 The scope of the package declaration is from the declaration itself to the end
5239 of the enclosing block (the same scope as the local() operator).
5240 Typically it would be the first declaration in a file to be included by
5241 the \*(L"require\*(R" operator.
5242 You can switch into a package in more than one place; it merely influences
5243 which symbol table is used by the compiler for the rest of that block.
5244 You can refer to variables and filehandles in other packages by prefixing
5245 the identifier with the package name and a single quote.
5246 If the package name is null, the \*(L"main\*(R" package as assumed.
5248 Only identifiers starting with letters are stored in the packages symbol
5250 All other symbols are kept in package \*(L"main\*(R".
5251 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
5252 and SIG are forced to be in package \*(L"main\*(R", even when used for
5253 other purposes than their built-in one.
5254 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
5255 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
5256 will be interpreted instead as a pattern match, a substitution
5259 Eval'ed strings are compiled in the package in which the eval was compiled
5261 (Assignments to $SIG{}, however, assume the signal handler specified is in the
5263 Qualify the signal handler name if you wish to have a signal handler in
5265 For an example, examine perldb.pl in the perl library.
5266 It initially switches to the DB package so that the debugger doesn't interfere
5267 with variables in the script you are trying to debug.
5268 At various points, however, it temporarily switches back to the main package
5269 to evaluate various expressions in the context of the main package.
5271 The symbol table for a package happens to be stored in the associative array
5272 of that name prepended with an underscore.
5273 The value in each entry of the associative array is
5274 what you are referring to when you use the *name notation.
5275 In fact, the following have the same effect (in package main, anyway),
5276 though the first is more
5277 efficient because it does the symbol table lookups at compile time:
5282 local($_main{'foo'}) = $_main{'bar'};
5285 You can use this to print out all the variables in a package, for instance.
5286 Here is dumpvar.pl from the perl library:
5293 \& local(*stab) = eval("*_$package");
5294 \& while (($key,$val) = each(%stab)) {
5296 \& local(*entry) = $val;
5297 \& if (defined $entry) {
5298 \& print "\e$$key = '$entry'\en";
5301 \& if (defined @entry) {
5302 \& print "\e@$key = (\en";
5303 \& foreach $num ($[ .. $#entry) {
5304 \& print " $num\et'",$entry[$num],"'\en";
5309 \& if ($key ne "_$package" && defined %entry) {
5310 \& print "\e%$key = (\en";
5311 \& foreach $key (sort keys(%entry)) {
5312 \& print " $key\et'",$entry{$key},"'\en";
5321 Note that, even though the subroutine is compiled in package dumpvar, the
5322 name of the subroutine is qualified so that its name is inserted into package
5325 Each programmer will, of course, have his or her own preferences in regards
5326 to formatting, but there are some general guidelines that will make your
5327 programs easier to read.
5329 Just because you CAN do something a particular way doesn't mean that
5330 you SHOULD do it that way.
5332 is designed to give you several ways to do anything, so consider picking
5333 the most readable one.
5336 open(FOO,$foo) || die "Can't open $foo: $!";
5340 die "Can't open $foo: $!" unless open(FOO,$foo);
5342 because the second way hides the main point of the statement in a
5346 print "Starting analysis\en" if $verbose;
5350 $verbose && print "Starting analysis\en";
5352 since the main point isn't whether the user typed -v or not.
5354 Similarly, just because an operator lets you assume default arguments
5355 doesn't mean that you have to make use of the defaults.
5356 The defaults are there for lazy systems programmers writing one-shot
5358 If you want your program to be readable, consider supplying the argument.
5360 Along the same lines, just because you
5362 omit parentheses in many places doesn't mean that you ought to:
5365 return print reverse sort num values array;
5366 return print(reverse(sort num (values(%array))));
5369 When in doubt, parenthesize.
5370 At the very least it will let some poor schmuck bounce on the % key in vi.
5372 Even if you aren't in doubt, consider the mental welfare of the person who
5373 has to maintain the code after you, and who will probably put parens in
5376 Don't go through silly contortions to exit a loop at the top or the
5379 provides the "last" operator so you can exit in the middle.
5380 Just outdent it a little to make it more visible:
5394 Don't be afraid to use loop labels\*(--they're there to enhance readability as
5395 well as to allow multi-level loop breaks.
5398 For portability, when using features that may not be implemented on every
5399 machine, test the construct in an eval to see if it fails.
5400 If you know what version or patchlevel a particular feature was implemented,
5401 you can test $] to see if it will be there.
5403 Choose mnemonic identifiers.
5411 switch, your script will be run under a debugging monitor.
5412 It will halt before the first executable statement and ask you for a
5415 Prints out a help message.
5420 Executes until it reaches the beginning of another statement.
5423 Executes over subroutine calls, until it reaches the beginning of the
5427 Executes statements until it has finished the current subroutine.
5430 Executes until the next breakpoint is reached.
5432 Continue to the specified line.
5433 Inserts a one-time-only breakpoint at the specified line.
5436 .Ip "l min+incr" 12 4
5437 List incr+1 lines starting at min.
5438 If min is omitted, starts where last listing left off.
5439 If incr is omitted, previous value of incr is used.
5440 .Ip "l min-max" 12 4
5441 List lines in the indicated range.
5443 List just the indicated line.
5447 List previous window.
5449 List window around line.
5450 .Ip "l subname" 12 4
5452 If it's a long subroutine it just lists the beginning.
5453 Use \*(L"l\*(R" to list more.
5454 .Ip "/pattern/" 12 4
5455 Regular expression search forward for pattern; the final / is optional.
5456 .Ip "?pattern?" 12 4
5457 Regular expression search backward for pattern; the final ? is optional.
5459 List lines that have breakpoints or actions.
5461 Lists the names of all subroutines.
5463 Toggle trace mode on or off.
5464 .Ip "b line condition" 12 4
5466 If line is omitted, sets a breakpoint on the
5467 line that is about to be executed.
5468 If a condition is specified, it is evaluated each time the statement is
5469 reached and a breakpoint is taken only if the condition is true.
5470 Breakpoints may only be set on lines that begin an executable statement.
5471 .Ip "b subname condition" 12 4
5472 Set breakpoint at first executable line of subroutine.
5475 If line is omitted, deletes the breakpoint on the
5476 line that is about to be executed.
5478 Delete all breakpoints.
5479 .Ip "a line command" 12 4
5480 Set an action for line.
5481 A multi-line command may be entered by backslashing the newlines.
5483 Delete all line actions.
5484 .Ip "< command" 12 4
5485 Set an action to happen before every debugger prompt.
5486 A multi-line command may be entered by backslashing the newlines.
5487 .Ip "> command" 12 4
5488 Set an action to happen after the prompt when you've just given a command
5489 to return to executing the script.
5490 A multi-line command may be entered by backslashing the newlines.
5491 .Ip "V package" 12 4
5492 List all variables in package.
5493 Default is main package.
5495 Redo a debugging command.
5496 If number is omitted, redoes the previous command.
5497 .Ip "! -number" 12 4
5498 Redo the command that was that many commands ago.
5499 .Ip "H -number" 12 4
5500 Display last n commands.
5501 Only commands longer than one character are listed.
5502 If number is omitted, lists them all.
5506 Execute command as a perl statement.
5507 A missing semicolon will be supplied.
5509 Same as \*(L"print DB'OUT expr\*(R".
5510 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
5511 may be redirected to.
5513 If you want to modify the debugger, copy perldb.pl from the perl library
5514 to your current directory and modify it as necessary.
5515 (You'll also have to put -I. on your command line.)
5516 You can do some customization by setting up a .perldb file which contains
5517 initialization code.
5518 For instance, you could make aliases like these:
5521 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
5522 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
5524 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
5527 .Sh "Setuid Scripts"
5529 is designed to make it easy to write secure setuid and setgid scripts.
5530 Unlike shells, which are based on multiple substitution passes on each line
5533 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
5534 Additionally, since the language has more built-in functionality, it
5535 has to rely less upon external (and possibly untrustworthy) programs to
5536 accomplish its purposes.
5538 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
5539 insecure, but this kernel feature can be disabled.
5542 can emulate the setuid and setgid mechanism when it notices the otherwise
5543 useless setuid/gid bits on perl scripts.
5544 If the kernel feature isn't disabled,
5546 will complain loudly that your setuid script is insecure.
5547 You'll need to either disable the kernel setuid script feature, or put
5548 a C wrapper around the script.
5550 When perl is executing a setuid script, it takes special precautions to
5551 prevent you from falling into any obvious traps.
5552 (In some ways, a perl script is more secure than the corresponding
5554 Any command line argument, environment variable, or input is marked as
5555 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
5556 command that invokes a subshell, or in any command that modifies files,
5557 directories or processes.
5558 Any variable that is set within an expression that has previously referenced
5559 a tainted value also becomes tainted (even if it is logically impossible
5560 for the tainted value to influence the variable).
5565 $foo = shift; # $foo is tainted
5566 $bar = $foo,\'bar\'; # $bar is also tainted
5567 $xxx = <>; # Tainted
5568 $path = $ENV{\'PATH\'}; # Tainted, but see below
5569 $abc = \'abc\'; # Not tainted
5572 system "echo $foo"; # Insecure
5573 system "/bin/echo", $foo; # Secure (doesn't use sh)
5574 system "echo $bar"; # Insecure
5575 system "echo $abc"; # Insecure until PATH set
5578 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
5579 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
5581 $path = $ENV{\'PATH\'}; # Not tainted
5582 system "echo $abc"; # Is secure now!
5585 open(FOO,"$foo"); # OK
5586 open(FOO,">$foo"); # Not OK
5588 open(FOO,"echo $foo|"); # Not OK, but...
5589 open(FOO,"-|") || exec \'echo\', $foo; # OK
5591 $zzz = `echo $foo`; # Insecure, zzz tainted
5593 unlink $abc,$foo; # Insecure
5594 umask $foo; # Insecure
5597 exec "echo $foo"; # Insecure
5598 exec "echo", $foo; # Secure (doesn't use sh)
5599 exec "sh", \'-c\', $foo; # Considered secure, alas
5602 The taintedness is associated with each scalar value, so some elements
5603 of an array can be tainted, and others not.
5605 If you try to do something insecure, you will get a fatal error saying
5606 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
5607 Note that you can still write an insecure system call or exec,
5608 but only by explicitly doing something like the last example above.
5609 You can also bypass the tainting mechanism by referencing
5612 presumes that if you reference a substring using $1, $2, etc, you knew
5613 what you were doing when you wrote the pattern:
5616 $ARGV[0] =~ /^\-P(\ew+)$/;
5617 $printer = $1; # Not tainted
5620 This is fairly secure since \ew+ doesn't match shell metacharacters.
5621 Use of .+ would have been insecure, but
5623 doesn't check for that, so you must be careful with your patterns.
5624 This is the ONLY mechanism for untainting user supplied filenames if you
5625 want to do file operations on them (unless you make $> equal to $<).
5627 It's also possible to get into trouble with other operations that don't care
5628 whether they use tainted values.
5629 Make judicious use of the file tests in dealing with any user-supplied
5631 When possible, do opens and such after setting $> = $<.
5633 doesn't prevent you from opening tainted filenames for reading, so be
5634 careful what you print out.
5635 The tainting mechanism is intended to prevent stupid mistakes, not to remove
5636 the need for thought.
5639 uses PATH in executing subprocesses, and in finding the script if \-S
5641 HOME or LOGDIR are used if chdir has no argument.
5645 uses no environment variables, except to make them available
5646 to the script being executed, and to child processes.
5647 However, scripts running setuid would do well to execute the following lines
5648 before doing anything else, just to keep people honest:
5652 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
5653 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
5654 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
5658 Larry Wall <lwall@netlabs.com>
5660 MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
5662 /tmp/perl\-eXXXXXX temporary file for
5666 a2p awk to perl translator
5668 s2p sed to perl translator
5670 Compilation errors will tell you the line number of the error, with an
5671 indication of the next token or token type that was to be examined.
5672 (In the case of a script passed to
5678 is counted as one line.)
5680 Setuid scripts have additional constraints that can produce error messages
5681 such as \*(L"Insecure dependency\*(R".
5682 See the section on setuid scripts.
5686 users should take special note of the following:
5688 Semicolons are required after all simple statements in
5691 is not a statement delimiter.
5693 Curly brackets are required on ifs and whiles.
5695 Variables begin with $ or @ in
5698 Arrays index from 0 unless you set $[.
5699 Likewise string positions in substr() and index().
5701 You have to decide whether your array has numeric or string indices.
5703 Associative array values do not spring into existence upon mere reference.
5705 You have to decide whether you want to use string or numeric comparisons.
5707 Reading an input line does not split it for you. You get to split it yourself
5711 operator has different arguments.
5713 The current input line is normally in $_, not $0.
5714 It generally does not have the newline stripped.
5715 ($0 is the name of the program executed.)
5717 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
5722 statement does not add field and record separators unless you set
5725 You must open your files before you print to them.
5727 The range operator is \*(L".\|.\*(R", not comma.
5728 (The comma operator works as in C.)
5730 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
5731 (\*(L"~\*(R" is the one's complement operator, as in C.)
5733 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
5734 (\*(L"^\*(R" is the XOR operator, as in C.)
5736 The concatenation operator is \*(L".\*(R", not the null string.
5737 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
5738 since the third slash would be interpreted as a division operator\*(--the
5739 tokener is in fact slightly context sensitive for operators like /, ?, and <.
5740 And in fact, . itself can be the beginning of a number.)
5748 The following variables work differently
5752 ARGC \h'|2.5i'$#ARGV
5754 FILENAME\h'|2.5i'$ARGV
5755 FNR \h'|2.5i'$. \- something
5756 FS \h'|2.5i'(whatever you like)
5757 NF \h'|2.5i'$#Fld, or some such
5762 RLENGTH \h'|2.5i'length($&)
5764 RSTART \h'|2.5i'length($\`)
5769 When in doubt, run the
5771 construct through a2p and see what it gives you.
5773 Cerebral C programmers should take note of the following:
5775 Curly brackets are required on ifs and whiles.
5777 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
5788 There's no switch statement.
5790 Variables begin with $ or @ in
5793 Printf does not implement *.
5795 Comments begin with #, not /*.
5797 You can't take the address of anything.
5799 ARGV must be capitalized.
5801 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
5803 Signal handlers deal with signal names, not numbers.
5807 programmers should take note of the following:
5809 Backreferences in substitutions use $ rather than \e.
5811 The pattern matching metacharacters (, ), and | do not have backslashes in front.
5813 The range operator is .\|. rather than comma.
5815 Sharp shell programmers should take note of the following:
5817 The backtick operator does variable interpretation without regard to the
5818 presence of single quotes in the command.
5820 The backtick operator does no translation of the return value, unlike csh.
5822 Shells (especially csh) do several levels of substitution on each command line.
5824 does substitution only in certain constructs such as double quotes,
5825 backticks, angle brackets and search patterns.
5827 Shells interpret scripts a little bit at a time.
5829 compiles the whole program before executing it.
5831 The arguments are available via @ARGV, not $1, $2, etc.
5833 The environment is not automatically made available as variables.
5834 .SH ERRATA\0AND\0ADDENDA
5836 .I Programming\0Perl ,
5837 has the following omissions and goofs.
5839 On page 5, the examples which read
5846 eval "exec /usr/bin/perl
5850 On page 195, the equivalent to the System V sum program only works for
5851 very small files. To do larger files, use
5855 $checksum = unpack("%32C*",<>) % 32767;
5859 The descriptions of alarm and sleep refer to signal SIGALARM. These
5860 should refer to SIGALRM.
5864 switch to set the initial value of $/ was added to Perl after the book
5869 switch now does automatic line ending processing.
5871 The qx// construct is now a synonym for backticks.
5873 $0 may now be assigned to set the argument displayed by
5876 The new @###.## format was omitted accidentally from the description
5879 It wasn't known at press time that s///ee caused multiple evaluations of
5880 the replacement expression. This is to be construed as a feature.
5882 (LIST) x $count now does array replication.
5884 There is now no limit on the number of parentheses in a regular expression.
5886 In double-quote context, more escapes are supported: \ee, \ea, \ex1b, \ec[,
5887 \el, \eL, \eu, \eU, \eE. The latter five control up/lower case translation.
5891 variable may now be set to a multi-character delimiter.
5893 There is now a g modifier on ordinary pattern matching that causes it
5894 to iterate through a string finding multiple matches.
5896 All of the $^X variables are new except for $^T.
5898 The default top-of-form format for FILEHANDLE is now FILEHANDLE_TOP rather
5901 The eval {} and sort {} constructs were added in version 4.018.
5903 The v and V (little-endian) template options for pack and unpack were
5908 is at the mercy of your machine's definitions of various operations
5909 such as type casting, atof() and sprintf().
5911 If your stdio requires an seek or eof between reads and writes on a particular
5914 (This doesn't apply to sysread() and syswrite().)
5916 While none of the built-in data types have any arbitrary size limits (apart
5917 from memory size), there are still a few arbitrary limits:
5918 a given identifier may not be longer than 255 characters,
5919 and no component of your PATH may be longer than 255 if you use \-S.
5922 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell