2 ''' $Header: perl.man.1,v 3.0.1.2 89/11/17 15:30:03 lwall Locked $
4 ''' $Log: perl.man.1,v $
5 ''' Revision 3.0.1.2 89/11/17 15:30:03 lwall
6 ''' patch5: fixed some manual typos and indent problems
8 ''' Revision 3.0.1.1 89/11/11 04:41:22 lwall
9 ''' patch2: explained about sh and ${1+"$@"}
10 ''' patch2: documented that space must separate word and '' string
12 ''' Revision 3.0 89/10/18 15:21:29 lwall
34 ''' Set up \*(-- to give an unbreakable dash;
35 ''' string Tr holds user defined translation string.
36 ''' Bell System Logo is used as a dummy character.
41 .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
42 .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
59 perl \- Practical Extraction and Report Language
62 [options] filename args
65 is an interpreted language optimized for scanning arbitrary text files,
66 extracting information from those text files, and printing reports based
68 It's also a good language for many system management tasks.
69 The language is intended to be practical (easy to use, efficient, complete)
70 rather than beautiful (tiny, elegant, minimal).
71 It combines (in the author's opinion, anyway) some of the best features of C,
72 \fIsed\fR, \fIawk\fR, and \fIsh\fR,
73 so people familiar with those languages should have little difficulty with it.
74 (Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
76 Expression syntax corresponds quite closely to C expression syntax.
77 Unlike most Unix utilities,
79 does not arbitrarily limit the size of your data\*(--if you've got
82 can slurp in your whole file as a single string.
83 Recursion is of unlimited depth.
84 And the hash tables used by associative arrays grow as necessary to prevent
87 uses sophisticated pattern matching techniques to scan large amounts of
89 Although optimized for scanning text,
91 can also deal with binary data, and can make dbm files look like associative
92 arrays (where dbm is available).
95 scripts are safer than C programs
96 through a dataflow tracing mechanism which prevents many stupid security holes.
97 If you have a problem that would ordinarily use \fIsed\fR
98 or \fIawk\fR or \fIsh\fR, but it
99 exceeds their capabilities or must run a little faster,
100 and you don't want to write the silly thing in C, then
103 There are also translators to turn your
114 looks for your script in one of the following places:
116 Specified line by line via
118 switches on the command line.
120 Contained in the file specified by the first filename on the command line.
121 (Note that systems supporting the #! notation invoke interpreters this way.)
123 Passed in implicitly via standard input.
124 This only works if there are no filename arguments\*(--to pass
127 script you must explicitly specify a \- for the script name.
129 After locating your script,
131 compiles it to an internal form.
132 If the script is syntactically correct, it is executed.
134 Note: on first reading this section may not make much sense to you. It's here
135 at the front for easy reference.
137 A single-character option may be combined with the following option, if any.
138 This is particularly useful when invoking a script using the #! construct which
139 only allows one argument. Example:
143 #!/usr/bin/perl \-spi.bak # same as \-s \-p \-i.bak
150 turns on autosplit mode when used with a
154 An implicit split command to the @F array
155 is done as the first thing inside the implicit while loop produced by
162 perl \-ane \'print pop(@F), "\en";\'
168 print pop(@F), "\en";
174 runs the script under the perl debugger.
175 See the section on Debugging.
178 sets debugging flags.
179 To watch how it executes your script, use
181 (This only works if debugging is compiled into your
183 Another nice value is \-D1024, which lists your compiled syntax tree.
184 And \-D512 displays compiled regular expressions.
186 .BI \-e " commandline"
187 may be used to enter one line of script.
190 commands may be given to build up a multi-line script.
195 will not look for a script filename in the argument list.
198 specifies that files processed by the <> construct are to be edited
200 It does this by renaming the input file, opening the output file by the
201 same name, and selecting that output file as the default for print statements.
202 The extension, if supplied, is added to the name of the
203 old file to make a backup copy.
204 If no extension is supplied, no backup is made.
205 Saying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
210 #!/usr/bin/perl \-pi.bak
213 which is equivalent to
218 if ($ARGV ne $oldargv) {
219 rename($ARGV, $ARGV . \'.bak\');
220 open(ARGVOUT, ">$ARGV");
227 print; # this prints to original filename
234 form doesn't need to compare $ARGV to $oldargv to know when
235 the filename has changed.
236 It does, however, use ARGVOUT for the selected filehandle.
239 is restored as the default output filehandle after the loop.
241 You can use eof to locate the end of each input file, in case you want
242 to append to each file, or reset line numbering (see example under eof).
245 may be used in conjunction with
247 to tell the C preprocessor where to look for include files.
248 By default /usr/include and /usr/lib/perl are searched.
253 to assume the following loop around your script, which makes it iterate
254 over filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
259 .\|.\|. # your script goes here
263 Note that the lines are not printed by default.
266 to have lines printed.
267 Here is an efficient way to delete all files older than a week:
270 find . \-mtime +7 \-print | perl \-ne \'chop;unlink;\'
273 This is faster than using the \-exec switch of find because you don't have to
274 start a process on every filename found.
279 to assume the following loop around your script, which makes it iterate
280 over filename arguments somewhat like \fIsed\fR:
285 .\|.\|. # your script goes here
291 Note that the lines are printed automatically.
292 To suppress printing use the
302 causes your script to be run through the C preprocessor before
305 (Since both comments and cpp directives begin with the # character,
306 you should avoid starting comments with any words recognized
307 by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
310 enables some rudimentary switch parsing for switches on the command line
311 after the script name but before any filename arguments (or before a \-\|\-).
312 Any switch found there is removed from @ARGV and sets the corresponding variable in the
315 The following script prints \*(L"true\*(R" if and only if the script is
316 invoked with a \-xyz switch.
321 if ($xyz) { print "true\en"; }
328 use the PATH environment variable to search for the script
329 (unless the name of the script starts with a slash).
330 Typically this is used to emulate #! startup on machines that don't
331 support #!, in the following manner:
335 eval "exec /usr/bin/perl \-S $0 $*"
336 if $running_under_some_shell;
339 The system ignores the first line and feeds the script to /bin/sh,
340 which proceeds to try to execute the
342 script as a shell script.
343 The shell executes the second line as a normal shell command, and thus
347 On some systems $0 doesn't always contain the full pathname,
352 to search for the script if necessary.
355 locates the script, it parses the lines and ignores them because
356 the variable $running_under_some_shell is never true.
357 A better construct than $* would be ${1+"$@"}, which handles embedded spaces
358 and such in the filenames, but doesn't work if the script is being interpreted
360 In order to start up sh rather than csh, some systems may have to replace the
361 #! line with a line containing just
362 a colon, which will be politely ignored by perl.
367 to dump core after compiling your script.
368 You can then take this core dump and turn it into an executable file
369 by using the undump program (not supplied).
370 This speeds startup at the expense of some disk space (which you can
371 minimize by stripping the executable).
372 (Still, a "hello world" executable comes out to about 200K on my machine.)
373 If you are going to run your executable as a set-id program then you
374 should probably compile it using taintperl rather than normal perl.
375 If you want to execute a portion of your script before dumping, use the
376 dump operator instead.
381 to do unsafe operations.
382 Currently the only \*(L"unsafe\*(R" operation is the unlinking of directories while
383 running as superuser.
386 prints the version and patchlevel of your
391 prints warnings about identifiers that are mentioned only once, and scalar
392 variables that are used before being set.
393 Also warns about redefined subroutines, and references to undefined
394 filehandles or filehandles opened readonly that you are attempting to
396 Also warns you if you use == on values that don't look like numbers, and if
397 your subroutines recurse more than 100 deep.
398 .Sh "Data Types and Objects"
401 has three data types: scalars, arrays of scalars, and
402 associative arrays of scalars.
403 Normal arrays are indexed by number, and associative arrays by string.
405 The interpretation of operations and values in perl sometimes
406 depends on the requirements
407 of the context around the operation or value.
408 There are three major contexts: string, numeric and array.
409 Certain operations return array values
410 in contexts wanting an array, and scalar values otherwise.
411 (If this is true of an operation it will be mentioned in the documentation
413 Operations which return scalars don't care whether the context is looking
414 for a string or a number, but
415 scalar variables and values are interpreted as strings or numbers
416 as appropriate to the context.
417 A scalar is interpreted as TRUE in the boolean sense if it is not the null
419 Booleans returned by operators are 1 for true and 0 or \'\' (the null
422 There are actually two varieties of null string: defined and undefined.
423 Undefined null strings are returned when there is no real value for something,
424 such as when there was an error, or at end of file, or when you refer
425 to an uninitialized variable or element of an array.
426 An undefined null string may become defined the first time you access it, but
427 prior to that you can use the defined() operator to determine whether the
428 value is defined or not.
430 References to scalar variables always begin with \*(L'$\*(R', even when referring
431 to a scalar that is part of an array.
436 $days \h'|2i'# a simple scalar variable
437 $days[28] \h'|2i'# 29th element of array @days
438 $days{\'Feb\'}\h'|2i'# one value from an associative array
439 $#days \h'|2i'# last index of array @days
441 but entire arrays or array slices are denoted by \*(L'@\*(R':
443 @days \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
444 @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
445 @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
447 and entire associative arrays are denoted by \*(L'%\*(R':
449 %days \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
452 Any of these eight constructs may serve as an lvalue,
453 that is, may be assigned to.
454 (It also turns out that an assignment is itself an lvalue in
455 certain contexts\*(--see examples under s, tr and chop.)
456 Assignment to a scalar evaluates the righthand side in a scalar context,
457 while assignment to an array or array slice evaluates the righthand side
460 You may find the length of array @days by evaluating
461 \*(L"$#days\*(R", as in
463 (Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
464 Assigning to $#days changes the length of the array.
465 Shortening an array by this method does not actually destroy any values.
466 Lengthening an array that was previously shortened recovers the values that
467 were in those elements.
468 You can also gain some measure of efficiency by preextending an array that
470 (You can also extend an array by assigning to an element that is off the
472 This differs from assigning to $#whatever in that intervening values
473 are set to null rather than recovered.)
474 You can truncate an array down to nothing by assigning the null list () to
476 The following are exactly equivalent
480 $#whatever = $[ \- 1;
484 Multi-dimensional arrays are not directly supported, but see the discussion
485 of the $; variable later for a means of emulating multiple subscripts with
486 an associative array.
488 Every data type has its own namespace.
489 You can, without fear of conflict, use the same name for a scalar variable,
490 an array, an associative array, a filehandle, a subroutine name, and/or
492 Since variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
493 or \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
494 with respect to variable names.
495 (They ARE reserved with respect to labels and filehandles, however, which
496 don't have an initial special character.
497 Hint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
498 Using uppercase filehandles also improves readability and protects you
499 from conflict with future reserved words.)
500 Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
502 Names which start with a letter may also contain digits and underscores.
503 Names which do not start with a letter are limited to one character,
504 e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
505 (Most of the one character names have a predefined significance to
509 Numeric literals are specified in any of the usual floating point or
521 String literals are delimited by either single or double quotes.
522 They work much like shell quotes:
523 double-quoted string literals are subject to backslash and variable
524 substitution; single-quoted strings are not (except for \e\' and \e\e).
525 The usual backslash rules apply for making characters such as newline, tab, etc.
526 You can also embed newlines directly in your strings, i.e. they can end on
527 a different line than they begin.
528 This is nice, but if you forget your trailing quote, the error will not be
531 finds another line containing the quote character, which
532 may be much further on in the script.
533 Variable substitution inside strings is limited to scalar variables, normal
534 array values, and array slices.
535 (In other words, identifiers beginning with $ or @, followed by an optional
536 bracketed expression as a subscript.)
537 The following code segment prints out \*(L"The price is $100.\*(R"
541 $Price = \'$100\';\h'|3.5i'# not interpreted
542 print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
545 Note that you can put curly brackets around the identifier to delimit it
546 from following alphanumerics.
547 Also note that a single quoted string must be separated from a preceding
548 word by a space, since single quote is a valid character in an identifier
551 Array values are interpolated into double-quoted strings by joining all the
552 elements of the array with the delimiter specified in the $" variable,
554 (Since in versions of perl prior to 3.0 the @ character was not a metacharacter
555 in double-quoted strings, the interpolation of @array, $array[EXPR],
556 @array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
557 referenced elsewhere in the program or is predefined.)
558 The following are equivalent:
562 $temp = join($",@ARGV);
568 Within search patterns (which also undergo double-quotish substitution)
569 there is a bad ambiguity: Is /$foo[bar]/ to be
570 interpreted as /${foo}[bar]/ (where [bar] is a character class for the
571 regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
573 If @foo doesn't otherwise exist, then it's obviously a character class.
574 If @foo exists, perl takes a good guess about [bar], and is almost always right.
575 If it does guess wrong, or if you're just plain paranoid,
576 you can force the correct interpretation with curly brackets as above.
578 A line-oriented form of quoting is based on the shell here-is syntax.
579 Following a << you specify a string to terminate the quoted material, and all lines
580 following the current line down to the terminating string are the value
582 The terminating string may be either an identifier (a word), or some
584 If quoted, the type of quotes you use determines the treatment of the text,
585 just as in regular quoting.
586 An unquoted identifier works like double quotes.
587 There must be no space between the << and the identifier.
588 (If you put a space it will be treated as a null identifier, which is
589 valid, and matches the first blank line\*(--see Merry Christmas example below.)
590 The terminating string must appear by itself (unquoted and with no surrounding
591 whitespace) on the terminating line.
594 print <<EOF; # same as above
598 print <<"EOF"; # same as above
602 print << x 10; # null identifier is delimiter
605 print <<`EOC`; # execute commands
610 print <<foo, <<bar; # you can stack them
617 Array literals are denoted by separating individual values by commas, and
618 enclosing the list in parentheses.
619 In a context not requiring an array value, the value of the array literal
620 is the value of the final element, as in the C comma operator.
625 @foo = (\'cc\', \'\-E\', $bar);
627 assigns the entire array value to array foo, but
629 $foo = (\'cc\', \'\-E\', $bar);
632 assigns the value of variable bar to variable foo.
633 Array lists may be assigned to if and only if each element of the list
637 ($a, $b, $c) = (1, 2, 3);
639 ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
641 The final element may be an array or an associative array:
643 ($a, $b, @rest) = split;
644 local($a, $b, %rest) = @_;
647 You can actually put an array anywhere in the list, but the first array
648 in the list will soak up all the values, and anything after it will get
650 This may be useful in a local().
652 An associative array literal contains pairs of values to be interpreted
653 as a key and a value:
657 # same as map assignment above
658 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
661 Array assignment in a scalar context returns the number of elements
662 produced by the expression on the right side of the assignment:
665 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
669 There are several other pseudo-literals that you should know about.
670 If a string is enclosed by backticks (grave accents), it first undergoes
671 variable substitution just like a double quoted string.
672 It is then interpreted as a command, and the output of that command
673 is the value of the pseudo-literal, like in a shell.
674 The command is executed each time the pseudo-literal is evaluated.
675 The status value of the command is returned in $? (see Predefined Names
676 for the interpretation of $?).
677 Unlike in \f2csh\f1, no translation is done on the return
678 data\*(--newlines remain newlines.
679 Unlike in any of the shells, single quotes do not hide variable names
680 in the command from interpretation.
681 To pass a $ through to the shell you need to hide it with a backslash.
683 Evaluating a filehandle in angle brackets yields the next line
684 from that file (newline included, so it's never false until EOF, at
685 which time an undefined value is returned).
686 Ordinarily you must assign that value to a variable,
687 but there is one situation where in which an automatic assignment happens.
688 If (and only if) the input symbol is the only thing inside the conditional of a
691 automatically assigned to the variable \*(L"$_\*(R".
692 (This may seem like an odd thing to you, but you'll use the construct
696 Anyway, the following lines are equivalent to each other:
700 while ($_ = <STDIN>) { print; }
701 while (<STDIN>) { print; }
702 for (\|;\|<STDIN>;\|) { print; }
703 print while $_ = <STDIN>;
718 will also work except in packages, where they would be interpreted as
719 local identifiers rather than global.)
720 Additional filehandles may be created with the
724 If a <FILEHANDLE> is used in a context that is looking for an array, an array
725 consisting of all the input lines is returned, one line per array element.
726 It's easy to make a LARGE data space this way, so use with care.
728 The null filehandle <> is special and can be used to emulate the behavior of
729 \fIsed\fR and \fIawk\fR.
730 Input from <> comes either from standard input, or from each file listed on
732 Here's how it works: the first time <> is evaluated, the ARGV array is checked,
733 and if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
735 The ARGV array is then processed as a list of filenames.
741 .\|.\|. # code for each line
747 unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
748 while ($ARGV = shift) {
751 .\|.\|. # code for each line
756 except that it isn't as cumbersome to say.
757 It really does shift array ARGV and put the current filename into
759 It also uses filehandle ARGV internally.
760 You can modify @ARGV before the first <> as long as you leave the first
761 filename at the beginning of the array.
762 Line numbers ($.) continue as if the input was one big happy file.
763 (But see example under eof for how to reset line numbers on each file.)
766 If you want to set @ARGV to your own list of files, go right ahead.
767 If you want to pass switches into your script, you can
768 put a loop on the front like this:
772 while ($_ = $ARGV[0], /\|^\-/\|) {
774 last if /\|^\-\|\-$\|/\|;
775 /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
776 /\|^\-v\|/ \|&& \|$verbose++;
777 .\|.\|. # other switches
780 .\|.\|. # code for each line
784 The <> symbol will return FALSE only once.
785 If you call it again after this it will assume you are processing another
786 @ARGV list, and if you haven't set @ARGV, will input from
789 If the string inside the angle brackets is a reference to a scalar variable
791 then that variable contains the name of the filehandle to input from.
793 If the string inside angle brackets is not a filehandle, it is interpreted
794 as a filename pattern to be globbed, and either an array of filenames or the
795 next filename in the list is returned, depending on context.
796 One level of $ interpretation is done first, but you can't say <$foo>
797 because that's an indirect filehandle as explained in the previous
799 You could insert curly brackets to force interpretation as a
800 filename glob: <${foo}>.
812 open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
819 In fact, it's currently implemented that way.
820 (Which means it will not work on filenames with spaces in them unless
821 you have /bin/csh on your machine.)
822 Of course, the shortest way to do the above is:
832 script consists of a sequence of declarations and commands.
833 The only things that need to be declared in
835 are report formats and subroutines.
836 See the sections below for more information on those declarations.
837 All uninitialized user-created objects are assumed to
838 start with a null or 0 value until they
839 are defined by some explicit operation such as assignment.
840 The sequence of commands is executed just once, unlike in
844 scripts, where the sequence of commands is executed for each input line.
845 While this means that you must explicitly loop over the lines of your input file
846 (or files), it also means you have much more control over which files and which
848 (Actually, I'm lying\*(--it is possible to do an implicit loop with either the
854 A declaration can be put anywhere a command can, but has no effect on the
855 execution of the primary sequence of commands--declarations all take effect
857 Typically all the declarations are put at the beginning or the end of the script.
860 is, for the most part, a free-form language.
861 (The only exception to this is format declarations, for fairly obvious reasons.)
862 Comments are indicated by the # character, and extend to the end of the line.
863 If you attempt to use /* */ C comments, it will be interpreted either as
864 division or pattern matching, depending on the context.
866 .Sh "Compound statements"
869 a sequence of commands may be treated as one command by enclosing it
871 We will call this a BLOCK.
873 The following compound commands may be used to control flow:
878 if (EXPR) BLOCK else BLOCK
879 if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
880 LABEL while (EXPR) BLOCK
881 LABEL while (EXPR) BLOCK continue BLOCK
882 LABEL for (EXPR; EXPR; EXPR) BLOCK
883 LABEL foreach VAR (ARRAY) BLOCK
884 LABEL BLOCK continue BLOCK
887 Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
889 This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
890 If you want to write conditionals without curly brackets there are several
892 The following all do the same thing:
896 if (!open(foo)) { die "Can't open $foo: $!"; }
897 die "Can't open $foo: $!" unless open(foo);
898 open(foo) || die "Can't open $foo: $!"; # foo or bust!
899 open(foo) ? die "Can't open $foo: $!" : \'hi mom\';
900 # a bit exotic, that last one
906 statement is straightforward.
907 Since BLOCKs are always bounded by curly brackets, there is never any
908 ambiguity about which
917 the sense of the test is reversed.
921 statement executes the block as long as the expression is true
922 (does not evaluate to the null string or 0).
923 The LABEL is optional, and if present, consists of an identifier followed by
925 The LABEL identifies the loop for the loop control statements
933 BLOCK, it is always executed just before
934 the conditional is about to be evaluated again, similarly to the third part
938 Thus it can be used to increment a loop variable, even when the loop has
939 been continued via the
941 statement (similar to the C \*(L"continue\*(R" statement).
945 is replaced by the word
947 the sense of the test is reversed, but the conditional is still tested before
954 statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
955 is true if the value of the last command in that block is true.
959 loop works exactly like the corresponding
965 for ($i = 1; $i < 10; $i++) {
979 The foreach loop iterates over a normal array value and sets the variable
980 VAR to be each element of the array in turn.
981 The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
982 so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
983 If VAR is omitted, $_ is set to each value.
984 If ARRAY is an actual array (as opposed to an expression returning an array
985 value), you can modify each element of the array
986 by modifying VAR inside the loop.
991 for (@ary) { s/foo/bar/; }
993 foreach $elem (@elements) {
998 for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
999 print $_, "\en"; sleep(1);
1002 for (1..15) { print "Merry Christmas\en"; }
1005 foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'}) {
1006 print "Item: $item\en";
1011 The BLOCK by itself (labeled or not) is equivalent to a loop that executes
1013 Thus you can use any of the loop control statements in it to leave or
1018 This construct is particularly nice for doing case structures.
1023 if (/^abc/) { $abc = 1; last foo; }
1024 if (/^def/) { $def = 1; last foo; }
1025 if (/^xyz/) { $xyz = 1; last foo; }
1030 There is no official switch statement in perl, because there
1031 are already several ways to write the equivalent.
1032 In addition to the above, you could write
1037 $abc = 1, last foo if /^abc/;
1038 $def = 1, last foo if /^def/;
1039 $xyz = 1, last foo if /^xyz/;
1047 /^abc/ && do { $abc = 1; last foo; }
1048 /^def/ && do { $def = 1; last foo; }
1049 /^xyz/ && do { $xyz = 1; last foo; }
1057 /^abc/ && ($abc = 1, last foo);
1058 /^def/ && ($def = 1, last foo);
1059 /^xyz/ && ($xyz = 1, last foo);
1067 { $abc = 1; last foo; }
1069 { $def = 1; last foo; }
1071 { $xyz = 1; last foo; }
1076 As it happens, these are all optimized internally to a switch structure,
1077 so perl jumps directly to the desired statement, and you needn't worry
1078 about perl executing a lot of unnecessary statements when you have a string
1079 of 50 elsifs, as long as you are testing the same simple scalar variable
1080 using ==, eq, or pattern matching as above.
1081 (If you're curious as to whether the optimizer has done this for a particular
1082 case statement, you can use the \-D1024 switch to list the syntax tree
1084 .Sh "Simple statements"
1085 The only kind of simple statement is an expression evaluated for its side
1087 Every expression (simple statement) must be terminated with a semicolon.
1088 Note that this is like C, but unlike Pascal (and
1091 Any simple statement may optionally be followed by a
1092 single modifier, just before the terminating semicolon.
1093 The possible modifiers are:
1107 modifiers have the expected semantics.
1112 modifiers also have the expected semantics (conditional evaluated first),
1113 except when applied to a do-BLOCK command,
1114 in which case the block executes once before the conditional is evaluated.
1115 This is so that you can write loops like:
1122 } until $_ \|eq \|".\|\e\|n";
1127 operator below. Note also that the loop control commands described later will
1128 NOT work in this construct, since modifiers don't take loop labels.
1133 expressions work almost exactly like C expressions, only the differences
1134 will be mentioned here.
1140 The exponentiation operator.
1142 The exponentiation assignment operator.
1144 The null list, used to initialize an array to null.
1146 Concatenation of two strings.
1148 The concatenation assignment operator.
1150 String equality (== is numeric equality).
1151 For a mnemonic just think of \*(L"eq\*(R" as a string.
1152 (If you are used to the
1154 behavior of using == for either string or numeric equality
1155 based on the current form of the comparands, beware!
1156 You must be explicit here.)
1158 String inequality (!= is numeric inequality).
1162 String greater than.
1164 String less than or equal.
1166 String greater than or equal.
1168 Certain operations search or modify the string \*(L"$_\*(R" by default.
1169 This operator makes that kind of operation work on some other string.
1170 The right argument is a search pattern, substitution, or translation.
1171 The left argument is what is supposed to be searched, substituted, or
1172 translated instead of the default \*(L"$_\*(R".
1173 The return value indicates the success of the operation.
1174 (If the right argument is an expression other than a search pattern,
1175 substitution, or translation, it is interpreted as a search pattern
1177 This is less efficient than an explicit search, since the pattern must
1178 be compiled every time the expression is evaluated.)
1179 The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
1181 Just like =~ except the return value is negated.
1183 The repetition operator.
1184 Returns a string consisting of the left operand repeated the
1185 number of times specified by the right operand.
1188 print \'\-\' x 80; # print row of dashes
1189 print \'\-\' x80; # illegal, x80 is identifier
1191 print "\et" x ($tab/8), \' \' x ($tab%8); # tab over
1195 The repetition assignment operator.
1197 The range operator, which is really two different operators depending
1199 In an array context, returns an array of values counting (by ones)
1200 from the left value to the right value.
1201 This is useful for writing \*(L"for (1..10)\*(R" loops and for doing
1202 slice operations on arrays.
1204 In a scalar context, .\|. returns a boolean value.
1205 The operator is bistable, like a flip-flop..
1206 Each .\|. operator maintains its own boolean state.
1207 It is false as long as its left operand is false.
1208 Once the left operand is true, the range operator stays true
1209 until the right operand is true,
1210 AFTER which the range operator becomes false again.
1211 (It doesn't become false till the next time the range operator is evaluated.
1212 It can become false on the same evaluation it became true, but it still returns
1214 The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
1215 and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
1216 The scalar .\|. operator is primarily intended for doing line number ranges
1218 the fashion of \fIsed\fR or \fIawk\fR.
1219 The precedence is a little lower than || and &&.
1220 The value returned is either the null string for false, or a sequence number
1221 (beginning with 1) for true.
1222 The sequence number is reset for each range encountered.
1223 The final sequence number in a range has the string \'E0\' appended to it, which
1224 doesn't affect its numeric value, but gives you something to search for if you
1225 want to exclude the endpoint.
1226 You can exclude the beginning point by waiting for the sequence number to be
1228 If either operand of scalar .\|. is static, that operand is implicitly compared
1229 to the $. variable, the current line number.
1234 As a scalar operator:
1235 if (101 .\|. 200) { print; } # print 2nd hundred lines
1237 next line if (1 .\|. /^$/); # skip header lines
1239 s/^/> / if (/^$/ .\|. eof()); # quote body
1242 As an array operator:
1243 for (101 .\|. 200) { print; } # print $_ 100 times
1245 @foo = @foo[$[ .\|. $#foo]; # an expensive no-op
1246 @foo = @foo[$#foo-4 .\|. $#foo]; # slice last 5 items
1251 This unary operator takes one argument, either a filename or a filehandle,
1252 and tests the associated file to see if something is true about it.
1253 If the argument is omitted, tests $_, except for \-t, which tests
1255 It returns 1 for true and \'\' for false, or the undefined value if the
1257 Precedence is higher than logical and relational operators, but lower than
1258 arithmetic operators.
1259 The operator may be any of:
1261 \-r File is readable by effective uid.
1262 \-w File is writable by effective uid.
1263 \-x File is executable by effective uid.
1264 \-o File is owned by effective uid.
1265 \-R File is readable by real uid.
1266 \-W File is writable by real uid.
1267 \-X File is executable by real uid.
1268 \-O File is owned by real uid.
1270 \-z File has zero size.
1271 \-s File has non-zero size.
1272 \-f File is a plain file.
1273 \-d File is a directory.
1274 \-l File is a symbolic link.
1275 \-p File is a named pipe (FIFO).
1276 \-S File is a socket.
1277 \-b File is a block special file.
1278 \-c File is a character special file.
1279 \-u File has setuid bit set.
1280 \-g File has setgid bit set.
1281 \-k File has sticky bit set.
1282 \-t Filehandle is opened to a tty.
1283 \-T File is a text file.
1284 \-B File is a binary file (opposite of \-T).
1287 The interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
1288 is based solely on the mode of the file and the uids and gids of the user.
1289 There may be other reasons you can't actually read, write or execute the file.
1290 Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and
1291 \-x and \-X return 1 if any execute bit is set in the mode.
1292 Scripts run by the superuser may thus need to do a stat() in order to determine
1293 the actual mode of the file, or temporarily set the uid to something else.
1301 next unless \-f $_; # ignore specials
1306 Note that \-s/a/b/ does not do a negated substitution.
1307 Saying \-exp($foo) still works as expected, however\*(--only single letters
1308 following a minus are interpreted as file tests.
1310 The \-T and \-B switches work as follows.
1311 The first block or so of the file is examined for odd characters such as
1312 strange control codes or metacharacters.
1313 If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
1314 Also, any file containing null in the first block is considered a binary file.
1315 If \-T or \-B is used on a filehandle, the current stdio buffer is examined
1316 rather than the first block.
1317 Both \-T and \-B return TRUE on a null file, or a file at EOF when testing
1320 If any of the file tests (or either stat operator) are given the special
1321 filehandle consisting of a solitary underline, then the stat structure
1322 of the previous file test (or stat operator) is used, saving a system
1324 (This doesn't work with \-t, and you need to remember that lstat and -l
1325 will leave values in the stat structure for the symbolic link, not the
1330 print "Can do.\en" if -r $a || -w _ || -x _;
1334 print "Readable\en" if -r _;
1335 print "Writable\en" if -w _;
1336 print "Executable\en" if -x _;
1337 print "Setuid\en" if -u _;
1338 print "Setgid\en" if -g _;
1339 print "Sticky\en" if -k _;
1340 print "Text\en" if -T _;
1341 print "Binary\en" if -B _;
1345 Here is what C has that
1349 Address-of operator.
1351 Dereference-address operator.
1353 Type casting operator.
1357 does a certain amount of expression evaluation at compile time, whenever
1358 it determines that all of the arguments to an operator are static and have
1360 In particular, string concatenation happens at compile time between literals that don't do variable substitution.
1361 Backslash interpretation also happens at compile time.
1366 \'Now is the time for all\' . "\|\e\|n" .
1367 \'good men to come to.\'
1370 and this all reduces to one string internally.
1372 The autoincrement operator has a little extra built-in magic to it.
1373 If you increment a variable that is numeric, or that has ever been used in
1374 a numeric context, you get a normal increment.
1375 If, however, the variable has only been used in string contexts since it
1376 was set, and has a value that is not null and matches the
1377 pattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
1378 as a string, preserving each character within its range, with carry:
1381 print ++($foo = \'99\'); # prints \*(L'100\*(R'
1382 print ++($foo = \'a0\'); # prints \*(L'a1\*(R'
1383 print ++($foo = \'Az\'); # prints \*(L'Ba\*(R'
1384 print ++($foo = \'zz\'); # prints \*(L'aaa\*(R'
1387 The autodecrement is not magical.