2 ''' $Header: perl.man.1,v 3.0.1.4 90/03/12 16:44:33 lwall Locked $
4 ''' $Log: perl.man.1,v $
5 ''' Revision 3.0.1.4 90/03/12 16:44:33 lwall
6 ''' patch13: (LIST,) now legal
7 ''' patch13: improved LIST documentation
8 ''' patch13: example of if-elsif switch was wrong
10 ''' Revision 3.0.1.3 90/02/28 17:54:32 lwall
11 ''' patch9: @array in scalar context now returns length of array
12 ''' patch9: in manual, example of open and ?: was backwards
14 ''' Revision 3.0.1.2 89/11/17 15:30:03 lwall
15 ''' patch5: fixed some manual typos and indent problems
17 ''' Revision 3.0.1.1 89/11/11 04:41:22 lwall
18 ''' patch2: explained about sh and ${1+"$@"}
19 ''' patch2: documented that space must separate word and '' string
21 ''' Revision 3.0 89/10/18 15:21:29 lwall
43 ''' Set up \*(-- to give an unbreakable dash;
44 ''' string Tr holds user defined translation string.
45 ''' Bell System Logo is used as a dummy character.
50 .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
51 .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
68 perl \- Practical Extraction and Report Language
71 [options] filename args
74 is an interpreted language optimized for scanning arbitrary text files,
75 extracting information from those text files, and printing reports based
77 It's also a good language for many system management tasks.
78 The language is intended to be practical (easy to use, efficient, complete)
79 rather than beautiful (tiny, elegant, minimal).
80 It combines (in the author's opinion, anyway) some of the best features of C,
81 \fIsed\fR, \fIawk\fR, and \fIsh\fR,
82 so people familiar with those languages should have little difficulty with it.
83 (Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
85 Expression syntax corresponds quite closely to C expression syntax.
86 Unlike most Unix utilities,
88 does not arbitrarily limit the size of your data\*(--if you've got
91 can slurp in your whole file as a single string.
92 Recursion is of unlimited depth.
93 And the hash tables used by associative arrays grow as necessary to prevent
96 uses sophisticated pattern matching techniques to scan large amounts of
98 Although optimized for scanning text,
100 can also deal with binary data, and can make dbm files look like associative
101 arrays (where dbm is available).
104 scripts are safer than C programs
105 through a dataflow tracing mechanism which prevents many stupid security holes.
106 If you have a problem that would ordinarily use \fIsed\fR
107 or \fIawk\fR or \fIsh\fR, but it
108 exceeds their capabilities or must run a little faster,
109 and you don't want to write the silly thing in C, then
112 There are also translators to turn your
123 looks for your script in one of the following places:
125 Specified line by line via
127 switches on the command line.
129 Contained in the file specified by the first filename on the command line.
130 (Note that systems supporting the #! notation invoke interpreters this way.)
132 Passed in implicitly via standard input.
133 This only works if there are no filename arguments\*(--to pass
136 script you must explicitly specify a \- for the script name.
138 After locating your script,
140 compiles it to an internal form.
141 If the script is syntactically correct, it is executed.
143 Note: on first reading this section may not make much sense to you. It's here
144 at the front for easy reference.
146 A single-character option may be combined with the following option, if any.
147 This is particularly useful when invoking a script using the #! construct which
148 only allows one argument. Example:
152 #!/usr/bin/perl \-spi.bak # same as \-s \-p \-i.bak
159 turns on autosplit mode when used with a
163 An implicit split command to the @F array
164 is done as the first thing inside the implicit while loop produced by
171 perl \-ane \'print pop(@F), "\en";\'
177 print pop(@F), "\en";
183 runs the script under the perl debugger.
184 See the section on Debugging.
187 sets debugging flags.
188 To watch how it executes your script, use
190 (This only works if debugging is compiled into your
192 Another nice value is \-D1024, which lists your compiled syntax tree.
193 And \-D512 displays compiled regular expressions.
195 .BI \-e " commandline"
196 may be used to enter one line of script.
199 commands may be given to build up a multi-line script.
204 will not look for a script filename in the argument list.
207 specifies that files processed by the <> construct are to be edited
209 It does this by renaming the input file, opening the output file by the
210 same name, and selecting that output file as the default for print statements.
211 The extension, if supplied, is added to the name of the
212 old file to make a backup copy.
213 If no extension is supplied, no backup is made.
214 Saying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
219 #!/usr/bin/perl \-pi.bak
222 which is equivalent to
227 if ($ARGV ne $oldargv) {
228 rename($ARGV, $ARGV . \'.bak\');
229 open(ARGVOUT, ">$ARGV");
236 print; # this prints to original filename
243 form doesn't need to compare $ARGV to $oldargv to know when
244 the filename has changed.
245 It does, however, use ARGVOUT for the selected filehandle.
248 is restored as the default output filehandle after the loop.
250 You can use eof to locate the end of each input file, in case you want
251 to append to each file, or reset line numbering (see example under eof).
254 may be used in conjunction with
256 to tell the C preprocessor where to look for include files.
257 By default /usr/include and /usr/lib/perl are searched.
262 to assume the following loop around your script, which makes it iterate
263 over filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
268 .\|.\|. # your script goes here
272 Note that the lines are not printed by default.
275 to have lines printed.
276 Here is an efficient way to delete all files older than a week:
279 find . \-mtime +7 \-print | perl \-ne \'chop;unlink;\'
282 This is faster than using the \-exec switch of find because you don't have to
283 start a process on every filename found.
288 to assume the following loop around your script, which makes it iterate
289 over filename arguments somewhat like \fIsed\fR:
294 .\|.\|. # your script goes here
300 Note that the lines are printed automatically.
301 To suppress printing use the
311 causes your script to be run through the C preprocessor before
314 (Since both comments and cpp directives begin with the # character,
315 you should avoid starting comments with any words recognized
316 by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
319 enables some rudimentary switch parsing for switches on the command line
320 after the script name but before any filename arguments (or before a \-\|\-).
321 Any switch found there is removed from @ARGV and sets the corresponding variable in the
324 The following script prints \*(L"true\*(R" if and only if the script is
325 invoked with a \-xyz switch.
330 if ($xyz) { print "true\en"; }
337 use the PATH environment variable to search for the script
338 (unless the name of the script starts with a slash).
339 Typically this is used to emulate #! startup on machines that don't
340 support #!, in the following manner:
344 eval "exec /usr/bin/perl \-S $0 $*"
345 if $running_under_some_shell;
348 The system ignores the first line and feeds the script to /bin/sh,
349 which proceeds to try to execute the
351 script as a shell script.
352 The shell executes the second line as a normal shell command, and thus
356 On some systems $0 doesn't always contain the full pathname,
361 to search for the script if necessary.
364 locates the script, it parses the lines and ignores them because
365 the variable $running_under_some_shell is never true.
366 A better construct than $* would be ${1+"$@"}, which handles embedded spaces
367 and such in the filenames, but doesn't work if the script is being interpreted
369 In order to start up sh rather than csh, some systems may have to replace the
370 #! line with a line containing just
371 a colon, which will be politely ignored by perl.
376 to dump core after compiling your script.
377 You can then take this core dump and turn it into an executable file
378 by using the undump program (not supplied).
379 This speeds startup at the expense of some disk space (which you can
380 minimize by stripping the executable).
381 (Still, a "hello world" executable comes out to about 200K on my machine.)
382 If you are going to run your executable as a set-id program then you
383 should probably compile it using taintperl rather than normal perl.
384 If you want to execute a portion of your script before dumping, use the
385 dump operator instead.
390 to do unsafe operations.
391 Currently the only \*(L"unsafe\*(R" operation is the unlinking of directories while
392 running as superuser.
395 prints the version and patchlevel of your
400 prints warnings about identifiers that are mentioned only once, and scalar
401 variables that are used before being set.
402 Also warns about redefined subroutines, and references to undefined
403 filehandles or filehandles opened readonly that you are attempting to
405 Also warns you if you use == on values that don't look like numbers, and if
406 your subroutines recurse more than 100 deep.
407 .Sh "Data Types and Objects"
410 has three data types: scalars, arrays of scalars, and
411 associative arrays of scalars.
412 Normal arrays are indexed by number, and associative arrays by string.
414 The interpretation of operations and values in perl sometimes
415 depends on the requirements
416 of the context around the operation or value.
417 There are three major contexts: string, numeric and array.
418 Certain operations return array values
419 in contexts wanting an array, and scalar values otherwise.
420 (If this is true of an operation it will be mentioned in the documentation
422 Operations which return scalars don't care whether the context is looking
423 for a string or a number, but
424 scalar variables and values are interpreted as strings or numbers
425 as appropriate to the context.
426 A scalar is interpreted as TRUE in the boolean sense if it is not the null
428 Booleans returned by operators are 1 for true and 0 or \'\' (the null
431 There are actually two varieties of null string: defined and undefined.
432 Undefined null strings are returned when there is no real value for something,
433 such as when there was an error, or at end of file, or when you refer
434 to an uninitialized variable or element of an array.
435 An undefined null string may become defined the first time you access it, but
436 prior to that you can use the defined() operator to determine whether the
437 value is defined or not.
439 References to scalar variables always begin with \*(L'$\*(R', even when referring
440 to a scalar that is part of an array.
445 $days \h'|2i'# a simple scalar variable
446 $days[28] \h'|2i'# 29th element of array @days
447 $days{\'Feb\'}\h'|2i'# one value from an associative array
448 $#days \h'|2i'# last index of array @days
450 but entire arrays or array slices are denoted by \*(L'@\*(R':
452 @days \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
453 @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
454 @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
456 and entire associative arrays are denoted by \*(L'%\*(R':
458 %days \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
461 Any of these eight constructs may serve as an lvalue,
462 that is, may be assigned to.
463 (It also turns out that an assignment is itself an lvalue in
464 certain contexts\*(--see examples under s, tr and chop.)
465 Assignment to a scalar evaluates the righthand side in a scalar context,
466 while assignment to an array or array slice evaluates the righthand side
469 You may find the length of array @days by evaluating
470 \*(L"$#days\*(R", as in
472 (Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
473 Assigning to $#days changes the length of the array.
474 Shortening an array by this method does not actually destroy any values.
475 Lengthening an array that was previously shortened recovers the values that
476 were in those elements.
477 You can also gain some measure of efficiency by preextending an array that
479 (You can also extend an array by assigning to an element that is off the
481 This differs from assigning to $#whatever in that intervening values
482 are set to null rather than recovered.)
483 You can truncate an array down to nothing by assigning the null list () to
485 The following are exactly equivalent
489 $#whatever = $[ \- 1;
493 If you evaluate an array in a scalar context, it returns the length of
495 The following is always true:
498 @whatever == $#whatever \- $[ + 1;
502 Multi-dimensional arrays are not directly supported, but see the discussion
503 of the $; variable later for a means of emulating multiple subscripts with
504 an associative array.
505 You could also write a subroutine to turn multiple subscripts into a single
508 Every data type has its own namespace.
509 You can, without fear of conflict, use the same name for a scalar variable,
510 an array, an associative array, a filehandle, a subroutine name, and/or
512 Since variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
513 or \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
514 with respect to variable names.
515 (They ARE reserved with respect to labels and filehandles, however, which
516 don't have an initial special character.
517 Hint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
518 Using uppercase filehandles also improves readability and protects you
519 from conflict with future reserved words.)
520 Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
522 Names which start with a letter may also contain digits and underscores.
523 Names which do not start with a letter are limited to one character,
524 e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
525 (Most of the one character names have a predefined significance to
529 Numeric literals are specified in any of the usual floating point or
541 String literals are delimited by either single or double quotes.
542 They work much like shell quotes:
543 double-quoted string literals are subject to backslash and variable
544 substitution; single-quoted strings are not (except for \e\' and \e\e).
545 The usual backslash rules apply for making characters such as newline, tab, etc.
546 You can also embed newlines directly in your strings, i.e. they can end on
547 a different line than they begin.
548 This is nice, but if you forget your trailing quote, the error will not be
551 finds another line containing the quote character, which
552 may be much further on in the script.
553 Variable substitution inside strings is limited to scalar variables, normal
554 array values, and array slices.
555 (In other words, identifiers beginning with $ or @, followed by an optional
556 bracketed expression as a subscript.)
557 The following code segment prints out \*(L"The price is $100.\*(R"
561 $Price = \'$100\';\h'|3.5i'# not interpreted
562 print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
565 Note that you can put curly brackets around the identifier to delimit it
566 from following alphanumerics.
567 Also note that a single quoted string must be separated from a preceding
568 word by a space, since single quote is a valid character in an identifier
571 Array values are interpolated into double-quoted strings by joining all the
572 elements of the array with the delimiter specified in the $" variable,
574 (Since in versions of perl prior to 3.0 the @ character was not a metacharacter
575 in double-quoted strings, the interpolation of @array, $array[EXPR],
576 @array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
577 referenced elsewhere in the program or is predefined.)
578 The following are equivalent:
582 $temp = join($",@ARGV);
588 Within search patterns (which also undergo double-quotish substitution)
589 there is a bad ambiguity: Is /$foo[bar]/ to be
590 interpreted as /${foo}[bar]/ (where [bar] is a character class for the
591 regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
593 If @foo doesn't otherwise exist, then it's obviously a character class.
594 If @foo exists, perl takes a good guess about [bar], and is almost always right.
595 If it does guess wrong, or if you're just plain paranoid,
596 you can force the correct interpretation with curly brackets as above.
598 A line-oriented form of quoting is based on the shell here-is syntax.
599 Following a << you specify a string to terminate the quoted material, and all lines
600 following the current line down to the terminating string are the value
602 The terminating string may be either an identifier (a word), or some
604 If quoted, the type of quotes you use determines the treatment of the text,
605 just as in regular quoting.
606 An unquoted identifier works like double quotes.
607 There must be no space between the << and the identifier.
608 (If you put a space it will be treated as a null identifier, which is
609 valid, and matches the first blank line\*(--see Merry Christmas example below.)
610 The terminating string must appear by itself (unquoted and with no surrounding
611 whitespace) on the terminating line.
614 print <<EOF; # same as above
618 print <<"EOF"; # same as above
622 print << x 10; # null identifier is delimiter
625 print <<`EOC`; # execute commands
630 print <<foo, <<bar; # you can stack them
637 Array literals are denoted by separating individual values by commas, and
638 enclosing the list in parentheses:
644 In a context not requiring an array value, the value of the array literal
645 is the value of the final element, as in the C comma operator.
650 @foo = (\'cc\', \'\-E\', $bar);
652 assigns the entire array value to array foo, but
654 $foo = (\'cc\', \'\-E\', $bar);
657 assigns the value of variable bar to variable foo.
658 Note that the value of an actual array in a scalar context is the length
659 of the array; the following assigns to $foo the value 3:
663 @foo = (\'cc\', \'\-E\', $bar);
664 $foo = @foo; # $foo gets 3
667 You may have an optional comma before the closing parenthesis of an
668 array literal, so that you can say:
678 When a LIST is evaluated, each element of the list is evaluated in
679 an array context, and the resulting array value is interpolated into LIST
680 just as if each individual element were a member of LIST. Thus arrays
681 lose their identity in a LIST\*(--the list
685 contains all the elements of @foo followed by all the elements of @bar,
686 followed by all the elements returned by the subroutine named SomeSub.
688 A list value may also be subscripted like a normal array.
692 $time = (stat($file))[8]; # stat returns array value
693 $digit = ('a','b','c','d','e','f')[$digit-10];
694 return (pop(@foo),pop(@foo))[0];
698 Array lists may be assigned to if and only if each element of the list
702 ($a, $b, $c) = (1, 2, 3);
704 ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
706 The final element may be an array or an associative array:
708 ($a, $b, @rest) = split;
709 local($a, $b, %rest) = @_;
712 You can actually put an array anywhere in the list, but the first array
713 in the list will soak up all the values, and anything after it will get
715 This may be useful in a local().
717 An associative array literal contains pairs of values to be interpreted
718 as a key and a value:
722 # same as map assignment above
723 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
726 Array assignment in a scalar context returns the number of elements
727 produced by the expression on the right side of the assignment:
730 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
734 There are several other pseudo-literals that you should know about.
735 If a string is enclosed by backticks (grave accents), it first undergoes
736 variable substitution just like a double quoted string.
737 It is then interpreted as a command, and the output of that command
738 is the value of the pseudo-literal, like in a shell.
739 The command is executed each time the pseudo-literal is evaluated.
740 The status value of the command is returned in $? (see Predefined Names
741 for the interpretation of $?).
742 Unlike in \f2csh\f1, no translation is done on the return
743 data\*(--newlines remain newlines.
744 Unlike in any of the shells, single quotes do not hide variable names
745 in the command from interpretation.
746 To pass a $ through to the shell you need to hide it with a backslash.
748 Evaluating a filehandle in angle brackets yields the next line
749 from that file (newline included, so it's never false until EOF, at
750 which time an undefined value is returned).
751 Ordinarily you must assign that value to a variable,
752 but there is one situation where an automatic assignment happens.
753 If (and only if) the input symbol is the only thing inside the conditional of a
756 automatically assigned to the variable \*(L"$_\*(R".
757 (This may seem like an odd thing to you, but you'll use the construct
761 Anyway, the following lines are equivalent to each other:
765 while ($_ = <STDIN>) { print; }
766 while (<STDIN>) { print; }
767 for (\|;\|<STDIN>;\|) { print; }
768 print while $_ = <STDIN>;
783 will also work except in packages, where they would be interpreted as
784 local identifiers rather than global.)
785 Additional filehandles may be created with the
789 If a <FILEHANDLE> is used in a context that is looking for an array, an array
790 consisting of all the input lines is returned, one line per array element.
791 It's easy to make a LARGE data space this way, so use with care.
793 The null filehandle <> is special and can be used to emulate the behavior of
794 \fIsed\fR and \fIawk\fR.
795 Input from <> comes either from standard input, or from each file listed on
797 Here's how it works: the first time <> is evaluated, the ARGV array is checked,
798 and if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
800 The ARGV array is then processed as a list of filenames.
806 .\|.\|. # code for each line
812 unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
813 while ($ARGV = shift) {
816 .\|.\|. # code for each line
821 except that it isn't as cumbersome to say.
822 It really does shift array ARGV and put the current filename into
824 It also uses filehandle ARGV internally.
825 You can modify @ARGV before the first <> as long as you leave the first
826 filename at the beginning of the array.
827 Line numbers ($.) continue as if the input was one big happy file.
828 (But see example under eof for how to reset line numbers on each file.)
831 If you want to set @ARGV to your own list of files, go right ahead.
832 If you want to pass switches into your script, you can
833 put a loop on the front like this:
837 while ($_ = $ARGV[0], /\|^\-/\|) {
839 last if /\|^\-\|\-$\|/\|;
840 /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
841 /\|^\-v\|/ \|&& \|$verbose++;
842 .\|.\|. # other switches
845 .\|.\|. # code for each line
849 The <> symbol will return FALSE only once.
850 If you call it again after this it will assume you are processing another
851 @ARGV list, and if you haven't set @ARGV, will input from
854 If the string inside the angle brackets is a reference to a scalar variable
856 then that variable contains the name of the filehandle to input from.
858 If the string inside angle brackets is not a filehandle, it is interpreted
859 as a filename pattern to be globbed, and either an array of filenames or the
860 next filename in the list is returned, depending on context.
861 One level of $ interpretation is done first, but you can't say <$foo>
862 because that's an indirect filehandle as explained in the previous
864 You could insert curly brackets to force interpretation as a
865 filename glob: <${foo}>.
877 open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
884 In fact, it's currently implemented that way.
885 (Which means it will not work on filenames with spaces in them unless
886 you have /bin/csh on your machine.)
887 Of course, the shortest way to do the above is:
897 script consists of a sequence of declarations and commands.
898 The only things that need to be declared in
900 are report formats and subroutines.
901 See the sections below for more information on those declarations.
902 All uninitialized user-created objects are assumed to
903 start with a null or 0 value until they
904 are defined by some explicit operation such as assignment.
905 The sequence of commands is executed just once, unlike in
909 scripts, where the sequence of commands is executed for each input line.
910 While this means that you must explicitly loop over the lines of your input file
911 (or files), it also means you have much more control over which files and which
913 (Actually, I'm lying\*(--it is possible to do an implicit loop with either the
919 A declaration can be put anywhere a command can, but has no effect on the
920 execution of the primary sequence of commands--declarations all take effect
922 Typically all the declarations are put at the beginning or the end of the script.
925 is, for the most part, a free-form language.
926 (The only exception to this is format declarations, for fairly obvious reasons.)
927 Comments are indicated by the # character, and extend to the end of the line.
928 If you attempt to use /* */ C comments, it will be interpreted either as
929 division or pattern matching, depending on the context.
931 .Sh "Compound statements"
934 a sequence of commands may be treated as one command by enclosing it
936 We will call this a BLOCK.
938 The following compound commands may be used to control flow:
943 if (EXPR) BLOCK else BLOCK
944 if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
945 LABEL while (EXPR) BLOCK
946 LABEL while (EXPR) BLOCK continue BLOCK
947 LABEL for (EXPR; EXPR; EXPR) BLOCK
948 LABEL foreach VAR (ARRAY) BLOCK
949 LABEL BLOCK continue BLOCK
952 Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
954 This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
955 If you want to write conditionals without curly brackets there are several
957 The following all do the same thing:
961 if (!open(foo)) { die "Can't open $foo: $!"; }
962 die "Can't open $foo: $!" unless open(foo);
963 open(foo) || die "Can't open $foo: $!"; # foo or bust!
964 open(foo) ? \'hi mom\' : die "Can't open $foo: $!";
965 # a bit exotic, that last one
971 statement is straightforward.
972 Since BLOCKs are always bounded by curly brackets, there is never any
973 ambiguity about which
982 the sense of the test is reversed.
986 statement executes the block as long as the expression is true
987 (does not evaluate to the null string or 0).
988 The LABEL is optional, and if present, consists of an identifier followed by
990 The LABEL identifies the loop for the loop control statements
998 BLOCK, it is always executed just before
999 the conditional is about to be evaluated again, similarly to the third part
1003 Thus it can be used to increment a loop variable, even when the loop has
1004 been continued via the
1006 statement (similar to the C \*(L"continue\*(R" statement).
1010 is replaced by the word
1012 the sense of the test is reversed, but the conditional is still tested before
1013 the first iteration.
1019 statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
1020 is true if the value of the last command in that block is true.
1024 loop works exactly like the corresponding
1030 for ($i = 1; $i < 10; $i++) {
1044 The foreach loop iterates over a normal array value and sets the variable
1045 VAR to be each element of the array in turn.
1046 The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
1047 so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
1048 If VAR is omitted, $_ is set to each value.
1049 If ARRAY is an actual array (as opposed to an expression returning an array
1050 value), you can modify each element of the array
1051 by modifying VAR inside the loop.
1056 for (@ary) { s/foo/bar/; }
1058 foreach $elem (@elements) {
1063 for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
1064 print $_, "\en"; sleep(1);
1067 for (1..15) { print "Merry Christmas\en"; }
1070 foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'}) {
1071 print "Item: $item\en";
1076 The BLOCK by itself (labeled or not) is equivalent to a loop that executes
1078 Thus you can use any of the loop control statements in it to leave or
1083 This construct is particularly nice for doing case structures.
1088 if (/^abc/) { $abc = 1; last foo; }
1089 if (/^def/) { $def = 1; last foo; }
1090 if (/^xyz/) { $xyz = 1; last foo; }
1095 There is no official switch statement in perl, because there
1096 are already several ways to write the equivalent.
1097 In addition to the above, you could write
1102 $abc = 1, last foo if /^abc/;
1103 $def = 1, last foo if /^def/;
1104 $xyz = 1, last foo if /^xyz/;
1112 /^abc/ && do { $abc = 1; last foo; }
1113 /^def/ && do { $def = 1; last foo; }
1114 /^xyz/ && do { $xyz = 1; last foo; }
1122 /^abc/ && ($abc = 1, last foo);
1123 /^def/ && ($def = 1, last foo);
1124 /^xyz/ && ($xyz = 1, last foo);
1141 As it happens, these are all optimized internally to a switch structure,
1142 so perl jumps directly to the desired statement, and you needn't worry
1143 about perl executing a lot of unnecessary statements when you have a string
1144 of 50 elsifs, as long as you are testing the same simple scalar variable
1145 using ==, eq, or pattern matching as above.
1146 (If you're curious as to whether the optimizer has done this for a particular
1147 case statement, you can use the \-D1024 switch to list the syntax tree
1149 .Sh "Simple statements"
1150 The only kind of simple statement is an expression evaluated for its side
1152 Every expression (simple statement) must be terminated with a semicolon.
1153 Note that this is like C, but unlike Pascal (and
1156 Any simple statement may optionally be followed by a
1157 single modifier, just before the terminating semicolon.
1158 The possible modifiers are:
1172 modifiers have the expected semantics.
1177 modifiers also have the expected semantics (conditional evaluated first),
1178 except when applied to a do-BLOCK command,
1179 in which case the block executes once before the conditional is evaluated.
1180 This is so that you can write loops like:
1187 } until $_ \|eq \|".\|\e\|n";
1192 operator below. Note also that the loop control commands described later will
1193 NOT work in this construct, since modifiers don't take loop labels.
1198 expressions work almost exactly like C expressions, only the differences
1199 will be mentioned here.
1205 The exponentiation operator.
1207 The exponentiation assignment operator.
1209 The null list, used to initialize an array to null.
1211 Concatenation of two strings.
1213 The concatenation assignment operator.
1215 String equality (== is numeric equality).
1216 For a mnemonic just think of \*(L"eq\*(R" as a string.
1217 (If you are used to the
1219 behavior of using == for either string or numeric equality
1220 based on the current form of the comparands, beware!
1221 You must be explicit here.)
1223 String inequality (!= is numeric inequality).
1227 String greater than.
1229 String less than or equal.
1231 String greater than or equal.
1233 Certain operations search or modify the string \*(L"$_\*(R" by default.
1234 This operator makes that kind of operation work on some other string.
1235 The right argument is a search pattern, substitution, or translation.
1236 The left argument is what is supposed to be searched, substituted, or
1237 translated instead of the default \*(L"$_\*(R".
1238 The return value indicates the success of the operation.
1239 (If the right argument is an expression other than a search pattern,
1240 substitution, or translation, it is interpreted as a search pattern
1242 This is less efficient than an explicit search, since the pattern must
1243 be compiled every time the expression is evaluated.)
1244 The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
1246 Just like =~ except the return value is negated.
1248 The repetition operator.
1249 Returns a string consisting of the left operand repeated the
1250 number of times specified by the right operand.
1253 print \'\-\' x 80; # print row of dashes
1254 print \'\-\' x80; # illegal, x80 is identifier
1256 print "\et" x ($tab/8), \' \' x ($tab%8); # tab over
1260 The repetition assignment operator.
1262 The range operator, which is really two different operators depending
1264 In an array context, returns an array of values counting (by ones)
1265 from the left value to the right value.
1266 This is useful for writing \*(L"for (1..10)\*(R" loops and for doing
1267 slice operations on arrays.
1269 In a scalar context, .\|. returns a boolean value.
1270 The operator is bistable, like a flip-flop..
1271 Each .\|. operator maintains its own boolean state.
1272 It is false as long as its left operand is false.
1273 Once the left operand is true, the range operator stays true
1274 until the right operand is true,
1275 AFTER which the range operator becomes false again.
1276 (It doesn't become false till the next time the range operator is evaluated.
1277 It can become false on the same evaluation it became true, but it still returns
1279 The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
1280 and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
1281 The scalar .\|. operator is primarily intended for doing line number ranges
1283 the fashion of \fIsed\fR or \fIawk\fR.
1284 The precedence is a little lower than || and &&.
1285 The value returned is either the null string for false, or a sequence number
1286 (beginning with 1) for true.
1287 The sequence number is reset for each range encountered.
1288 The final sequence number in a range has the string \'E0\' appended to it, which
1289 doesn't affect its numeric value, but gives you something to search for if you
1290 want to exclude the endpoint.
1291 You can exclude the beginning point by waiting for the sequence number to be
1293 If either operand of scalar .\|. is static, that operand is implicitly compared
1294 to the $. variable, the current line number.
1299 As a scalar operator:
1300 if (101 .\|. 200) { print; } # print 2nd hundred lines
1302 next line if (1 .\|. /^$/); # skip header lines
1304 s/^/> / if (/^$/ .\|. eof()); # quote body
1307 As an array operator:
1308 for (101 .\|. 200) { print; } # print $_ 100 times
1310 @foo = @foo[$[ .\|. $#foo]; # an expensive no-op
1311 @foo = @foo[$#foo-4 .\|. $#foo]; # slice last 5 items
1316 This unary operator takes one argument, either a filename or a filehandle,
1317 and tests the associated file to see if something is true about it.
1318 If the argument is omitted, tests $_, except for \-t, which tests
1320 It returns 1 for true and \'\' for false, or the undefined value if the
1322 Precedence is higher than logical and relational operators, but lower than
1323 arithmetic operators.
1324 The operator may be any of:
1326 \-r File is readable by effective uid.
1327 \-w File is writable by effective uid.
1328 \-x File is executable by effective uid.
1329 \-o File is owned by effective uid.
1330 \-R File is readable by real uid.
1331 \-W File is writable by real uid.
1332 \-X File is executable by real uid.
1333 \-O File is owned by real uid.
1335 \-z File has zero size.
1336 \-s File has non-zero size.
1337 \-f File is a plain file.
1338 \-d File is a directory.
1339 \-l File is a symbolic link.
1340 \-p File is a named pipe (FIFO).
1341 \-S File is a socket.
1342 \-b File is a block special file.
1343 \-c File is a character special file.
1344 \-u File has setuid bit set.
1345 \-g File has setgid bit set.
1346 \-k File has sticky bit set.
1347 \-t Filehandle is opened to a tty.
1348 \-T File is a text file.
1349 \-B File is a binary file (opposite of \-T).
1352 The interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
1353 is based solely on the mode of the file and the uids and gids of the user.
1354 There may be other reasons you can't actually read, write or execute the file.
1355 Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and
1356 \-x and \-X return 1 if any execute bit is set in the mode.
1357 Scripts run by the superuser may thus need to do a stat() in order to determine
1358 the actual mode of the file, or temporarily set the uid to something else.
1366 next unless \-f $_; # ignore specials
1371 Note that \-s/a/b/ does not do a negated substitution.
1372 Saying \-exp($foo) still works as expected, however\*(--only single letters
1373 following a minus are interpreted as file tests.
1375 The \-T and \-B switches work as follows.
1376 The first block or so of the file is examined for odd characters such as
1377 strange control codes or metacharacters.
1378 If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
1379 Also, any file containing null in the first block is considered a binary file.
1380 If \-T or \-B is used on a filehandle, the current stdio buffer is examined
1381 rather than the first block.
1382 Both \-T and \-B return TRUE on a null file, or a file at EOF when testing
1385 If any of the file tests (or either stat operator) are given the special
1386 filehandle consisting of a solitary underline, then the stat structure
1387 of the previous file test (or stat operator) is used, saving a system
1389 (This doesn't work with \-t, and you need to remember that lstat and -l
1390 will leave values in the stat structure for the symbolic link, not the
1395 print "Can do.\en" if -r $a || -w _ || -x _;
1399 print "Readable\en" if -r _;
1400 print "Writable\en" if -w _;
1401 print "Executable\en" if -x _;
1402 print "Setuid\en" if -u _;
1403 print "Setgid\en" if -g _;
1404 print "Sticky\en" if -k _;
1405 print "Text\en" if -T _;
1406 print "Binary\en" if -B _;
1410 Here is what C has that
1414 Address-of operator.
1416 Dereference-address operator.
1418 Type casting operator.
1422 does a certain amount of expression evaluation at compile time, whenever
1423 it determines that all of the arguments to an operator are static and have
1425 In particular, string concatenation happens at compile time between literals that don't do variable substitution.
1426 Backslash interpretation also happens at compile time.
1431 \'Now is the time for all\' . "\|\e\|n" .
1432 \'good men to come to.\'
1435 and this all reduces to one string internally.
1437 The autoincrement operator has a little extra built-in magic to it.
1438 If you increment a variable that is numeric, or that has ever been used in
1439 a numeric context, you get a normal increment.
1440 If, however, the variable has only been used in string contexts since it
1441 was set, and has a value that is not null and matches the
1442 pattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
1443 as a string, preserving each character within its range, with carry:
1446 print ++($foo = \'99\'); # prints \*(L'100\*(R'
1447 print ++($foo = \'a0\'); # prints \*(L'a1\*(R'
1448 print ++($foo = \'Az\'); # prints \*(L'Ba\*(R'
1449 print ++($foo = \'zz\'); # prints \*(L'aaa\*(R'
1452 The autodecrement is not magical.