.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLSYN 1" .TH PERLSYN 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide" .SH "NAME" perlsyn \- Perl syntax .SH "DESCRIPTION" .IX Header "DESCRIPTION" A Perl script consists of a sequence of declarations and statements. The sequence of statements is executed just once, unlike in \fBsed\fR and \fBawk\fR scripts, where the sequence of statements is executed for each input line. While this means that you must explicitly loop over the lines of your input file (or files), it also means you have much more control over which files and which lines you look at. (Actually, I'm lying\*(--it is possible to do an implicit loop with either the \fB\-n\fR or \fB\-p\fR switch. It's just not the mandatory default like it is in \fBsed\fR and \fBawk\fR.) .PP Perl is, for the most part, a free-form language. (The only exception to this is format declarations, for obvious reasons.) Text from a \&\f(CW"#"\fR character until the end of the line is a comment, and is ignored. If you attempt to use \f(CW\*(C`/* */\*(C'\fR C\-style comments, it will be interpreted either as division or pattern matching, depending on the context, and \*(C+ \f(CW\*(C`//\*(C'\fR comments just look like a null regular expression, so don't do that. .Sh "Declarations" .IX Subsection "Declarations" The only things you need to declare in Perl are report formats and subroutines\*(--and even undefined subroutines can be handled through \s-1AUTOLOAD\s0. A variable holds the undefined value (\f(CW\*(C`undef\*(C'\fR) until it has been assigned a defined value, which is anything other than \f(CW\*(C`undef\*(C'\fR. When used as a number, \f(CW\*(C`undef\*(C'\fR is treated as \f(CW0\fR; when used as a string, it is treated the empty string, \&\f(CW""\fR; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat \f(CW\*(C`undef\*(C'\fR as a string or a number. Well, usually. Boolean contexts, such as: .PP .Vb 2 \& my $a; \& if ($a) {} .Ve .PP are exempt from warnings (because they care about truth rather than definedness). Operators such as \f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, \&\f(CW\*(C`\-=\*(C'\fR, and \f(CW\*(C`.=\*(C'\fR, that operate on undefined left values such as: .PP .Vb 2 \& my $a; \& $a++; .Ve .PP are also always exempt from such warnings. .PP A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements\*(--declarations all take effect at compile time. Typically all the declarations are put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with \f(CW\*(C`my()\*(C'\fR, you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables. .PP Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying \f(CW\*(C`sub name\*(C'\fR, thus: .PP .Vb 2 \& sub myname; \& $me = myname $0 or die "can't get myname"; .Ve .PP Note that \fImyname()\fR functions as a list operator, not as a unary operator; so be careful to use \f(CW\*(C`or\*(C'\fR instead of \f(CW\*(C`||\*(C'\fR in this case. However, if you were to declare the subroutine as \f(CW\*(C`sub myname ($)\*(C'\fR, then \&\f(CW\*(C`myname\*(C'\fR would function as a unary operator, so either \f(CW\*(C`or\*(C'\fR or \&\f(CW\*(C`||\*(C'\fR would work. .PP Subroutines declarations can also be loaded up with the \f(CW\*(C`require\*(C'\fR statement or both loaded and imported into your namespace with a \f(CW\*(C`use\*(C'\fR statement. See perlmod for details on this. .PP A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects. .Sh "Simple statements" .IX Subsection "Simple statements" The only kind of simple statement is an expression evaluated for its side effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. (A semicolon is still encouraged there if the block takes up more than one line, because you may eventually add another line.) Note that there are some operators like \f(CW\*(C`eval {}\*(C'\fR and \f(CW\*(C`do {}\*(C'\fR that look like compound statements, but aren't (they're just TERMs in an expression), and thus need an explicit termination if used as the last item in a statement. .PP Any simple statement may optionally be followed by a \fI\s-1SINGLE\s0\fR modifier, just before the terminating semicolon (or block ending). The possible modifiers are: .PP .Vb 5 \& if EXPR \& unless EXPR \& while EXPR \& until EXPR \& foreach EXPR .Ve .PP The \f(CW\*(C`if\*(C'\fR and \f(CW\*(C`unless\*(C'\fR modifiers have the expected semantics, presuming you're a speaker of English. The \f(CW\*(C`foreach\*(C'\fR modifier is an iterator: For each value in \s-1EXPR\s0, it aliases \f(CW$_\fR to the value and executes the statement. The \f(CW\*(C`while\*(C'\fR and \f(CW\*(C`until\*(C'\fR modifiers have the usual "\f(CW\*(C`while\*(C'\fR loop" semantics (conditional evaluated first), except when applied to a \f(CW\*(C`do\*(C'\fR\-BLOCK (or to the deprecated \f(CW\*(C`do\*(C'\fR\-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated. This is so that you can write loops like: .PP .Vb 4 \& do { \& $line = ; \& ... \& } until $line eq ".\en"; .Ve .PP See \*(L"do\*(R" in perlfunc. Note also that the loop control statements described later will \fI\s-1NOT\s0\fR work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for \f(CW\*(C`next\*(C'\fR) or around it (for \f(CW\*(C`last\*(C'\fR) to do that sort of thing. For \f(CW\*(C`next\*(C'\fR, just double the braces: .PP .Vb 4 \& do {{ \& next if $x == $y; \& # do something here \& }} until $x++ > $z; .Ve .PP For \f(CW\*(C`last\*(C'\fR, you have to be more elaborate: .PP .Vb 6 \& LOOP: { \& do { \& last if $x = $y**2; \& # do something here \& } while $x++ <= $z; \& } .Ve .Sh "Compound statements" .IX Subsection "Compound statements" In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval). .PP But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a \s-1BLOCK\s0. .PP The following compound statements may be used to control flow: .PP .Vb 9 \& if (EXPR) BLOCK \& if (EXPR) BLOCK else BLOCK \& if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK \& LABEL while (EXPR) BLOCK \& LABEL while (EXPR) BLOCK continue BLOCK \& LABEL for (EXPR; EXPR; EXPR) BLOCK \& LABEL foreach VAR (LIST) BLOCK \& LABEL foreach VAR (LIST) BLOCK continue BLOCK \& LABEL BLOCK continue BLOCK .Ve .PP Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not statements. This means that the curly brackets are \fIrequired\fR\-\-no dangling statements allowed. If you want to write conditionals without curly brackets there are several other ways to do it. The following all do the same thing: .PP .Vb 5 \& if (!open(FOO)) { die "Can't open $FOO: $!"; } \& die "Can't open $FOO: $!" unless open(FOO); \& open(FOO) or die "Can't open $FOO: $!"; # FOO or bust! \& open(FOO) ? 'hi mom' : die "Can't open $FOO: $!"; \& # a bit exotic, that last one .Ve .PP The \f(CW\*(C`if\*(C'\fR statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which \&\f(CW\*(C`if\*(C'\fR an \f(CW\*(C`else\*(C'\fR goes with. If you use \f(CW\*(C`unless\*(C'\fR in place of \f(CW\*(C`if\*(C'\fR, the sense of the test is reversed. .PP The \f(CW\*(C`while\*(C'\fR statement executes the block as long as the expression is true (does not evaluate to the null string \f(CW""\fR or \f(CW0\fR or \f(CW"0"\fR). The \s-1LABEL\s0 is optional, and if present, consists of an identifier followed by a colon. The \s-1LABEL\s0 identifies the loop for the loop control statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, and \f(CW\*(C`redo\*(C'\fR. If the \s-1LABEL\s0 is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically looking back your call-stack at run time to find the \s-1LABEL\s0. Such desperate behavior triggers a warning if you use the \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR flag. Unlike a \f(CW\*(C`foreach\*(C'\fR statement, a \f(CW\*(C`while\*(C'\fR statement never implicitly localises any variables. .PP If there is a \f(CW\*(C`continue\*(C'\fR \s-1BLOCK\s0, it is always executed just before the conditional is about to be evaluated again, just like the third part of a \&\f(CW\*(C`for\*(C'\fR loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the \f(CW\*(C`next\*(C'\fR statement (which is similar to the C \f(CW\*(C`continue\*(C'\fR statement). .Sh "Loop Control" .IX Subsection "Loop Control" The \f(CW\*(C`next\*(C'\fR command is like the \f(CW\*(C`continue\*(C'\fR statement in C; it starts the next iteration of the loop: .PP .Vb 4 \& LINE: while () { \& next LINE if /^#/; # discard comments \& ... \& } .Ve .PP The \f(CW\*(C`last\*(C'\fR command is like the \f(CW\*(C`break\*(C'\fR statement in C (as used in loops); it immediately exits the loop in question. The \&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed: .PP .Vb 4 \& LINE: while () { \& last LINE if /^$/; # exit when done with header \& ... \& } .Ve .PP The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without evaluating the conditional again. The \f(CW\*(C`continue\*(C'\fR block, if any, is \fInot\fR executed. This command is normally used by programs that want to lie to themselves about what was just input. .PP For example, when processing a file like \fI/etc/termcap\fR. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record. .PP .Vb 8 \& while (<>) { \& chomp; \& if (s/\e\e$//) { \& $_ .= <>; \& redo unless eof(); \& } \& # now process $_ \& } .Ve .PP which is Perl short-hand for the more explicitly written version: .PP .Vb 8 \& LINE: while (defined($line = )) { \& chomp($line); \& if ($line =~ s/\e\e$//) { \& $line .= ; \& redo LINE unless eof(); # not eof(ARGV)! \& } \& # now process $line \& } .Ve .PP Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or \f(CW\*(C`?pat?\*(C'\fR one-time matches: .PP .Vb 10 \& # inspired by :1,$g/fred/s//WILMA/ \& while (<>) { \& ?(fred)? && s//WILMA $1 WILMA/; \& ?(barney)? && s//BETTY $1 BETTY/; \& ?(homer)? && s//MARGE $1 MARGE/; \& } continue { \& print "$ARGV $.: $_"; \& close ARGV if eof(); # reset $. \& reset if eof(); # reset ?pat? \& } .Ve .PP If the word \f(CW\*(C`while\*(C'\fR is replaced by the word \f(CW\*(C`until\*(C'\fR, the sense of the test is reversed, but the conditional is still tested before the first iteration. .PP The loop control statements don't work in an \f(CW\*(C`if\*(C'\fR or \f(CW\*(C`unless\*(C'\fR, since they aren't loops. You can double the braces to make them such, though. .PP .Vb 5 \& if (/pattern/) {{ \& last if /fred/; \& next if /barney/; # same effect as "last", but doesn't document as well \& # do something here \& }} .Ve .PP This is caused by the fact that a block by itself acts as a loop that executes once, see \*(L"Basic BLOCKs and Switch Statements\*(R". .PP The form \f(CW\*(C`while/if BLOCK BLOCK\*(C'\fR, available in Perl 4, is no longer available. Replace any occurrence of \f(CW\*(C`if BLOCK\*(C'\fR by \f(CW\*(C`if (do BLOCK)\*(C'\fR. .Sh "For Loops" .IX Subsection "For Loops" Perl's C\-style \f(CW\*(C`for\*(C'\fR loop works like the corresponding \f(CW\*(C`while\*(C'\fR loop; that means that this: .PP .Vb 3 \& for ($i = 1; $i < 10; $i++) { \& ... \& } .Ve .PP is the same as this: .PP .Vb 6 \& $i = 1; \& while ($i < 10) { \& ... \& } continue { \& $i++; \& } .Ve .PP There is one minor difference: if variables are declared with \f(CW\*(C`my\*(C'\fR in the initialization section of the \f(CW\*(C`for\*(C'\fR, the lexical scope of those variables is exactly the \f(CW\*(C`for\*(C'\fR loop (the body of the loop and the control sections). .PP Besides the normal array index looping, \f(CW\*(C`for\*(C'\fR can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang. .PP .Vb 5 \& $on_a_tty = -t STDIN && -t STDOUT; \& sub prompt { print "yes? " if $on_a_tty } \& for ( prompt(); ; prompt() ) { \& # do something \& } .Ve .Sh "Foreach Loops" .IX Subsection "Foreach Loops" The \f(CW\*(C`foreach\*(C'\fR loop iterates over a normal list value and sets the variable \s-1VAR\s0 to be each element of the list in turn. If the variable is preceded with the keyword \f(CW\*(C`my\*(C'\fR, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with \f(CW\*(C`my\*(C'\fR, it uses that variable instead of the global one, but it's still localized to the loop. .PP The \f(CW\*(C`foreach\*(C'\fR keyword is actually a synonym for the \f(CW\*(C`for\*(C'\fR keyword, so you can use \f(CW\*(C`foreach\*(C'\fR for readability or \f(CW\*(C`for\*(C'\fR for brevity. (Or because the Bourne shell is more familiar to you than \fIcsh\fR, so writing \f(CW\*(C`for\*(C'\fR comes more naturally.) If \s-1VAR\s0 is omitted, \f(CW$_\fR is set to each value. .PP If any element of \s-1LIST\s0 is an lvalue, you can modify it by modifying \&\s-1VAR\s0 inside the loop. Conversely, if any element of \s-1LIST\s0 is \s-1NOT\s0 an lvalue, any attempt to modify that element will fail. In other words, the \f(CW\*(C`foreach\*(C'\fR loop index variable is an implicit alias for each item in the list that you're looping over. .PP If any part of \s-1LIST\s0 is an array, \f(CW\*(C`foreach\*(C'\fR will get very confused if you add or remove elements within the loop body, for example with \&\f(CW\*(C`splice\*(C'\fR. So don't do that. .PP \&\f(CW\*(C`foreach\*(C'\fR probably won't do what you expect if \s-1VAR\s0 is a tied or other special variable. Don't do that either. .PP Examples: .PP .Vb 1 \& for (@ary) { s/foo/bar/ } .Ve .PP .Vb 3 \& for my $elem (@elements) { \& $elem *= 2; \& } .Ve .PP .Vb 3 \& for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') { \& print $count, "\en"; sleep(1); \& } .Ve .PP .Vb 1 \& for (1..15) { print "Merry Christmas\en"; } .Ve .PP .Vb 3 \& foreach $item (split(/:[\e\e\en:]*/, $ENV{TERMCAP})) { \& print "Item: $item\en"; \& } .Ve .PP Here's how a C programmer might code up a particular algorithm in Perl: .PP .Vb 9 \& for (my $i = 0; $i < @ary1; $i++) { \& for (my $j = 0; $j < @ary2; $j++) { \& if ($ary1[$i] > $ary2[$j]) { \& last; # can't go to outer :-( \& } \& $ary1[$i] += $ary2[$j]; \& } \& # this is where that last takes me \& } .Ve .PP Whereas here's how a Perl programmer more comfortable with the idiom might do it: .PP .Vb 6 \& OUTER: for my $wid (@ary1) { \& INNER: for my $jet (@ary2) { \& next OUTER if $wid > $jet; \& $wid += $jet; \& } \& } .Ve .PP See how much easier this is? It's cleaner, safer, and faster. It's cleaner because it's less noisy. It's safer because if code gets added between the inner and outer loops later on, the new code won't be accidentally executed. The \f(CW\*(C`next\*(C'\fR explicitly iterates the other loop rather than merely terminating the inner one. And it's faster because Perl executes a \f(CW\*(C`foreach\*(C'\fR statement more rapidly than it would the equivalent \f(CW\*(C`for\*(C'\fR loop. .Sh "Basic BLOCKs and Switch Statements" .IX Subsection "Basic BLOCKs and Switch Statements" A \s-1BLOCK\s0 by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is \&\fI\s-1NOT\s0\fR true in \f(CW\*(C`eval{}\*(C'\fR, \f(CW\*(C`sub{}\*(C'\fR, or contrary to popular belief \&\f(CW\*(C`do{}\*(C'\fR blocks, which do \fI\s-1NOT\s0\fR count as loops.) The \f(CW\*(C`continue\*(C'\fR block is optional. .PP The \s-1BLOCK\s0 construct is particularly nice for doing case structures. .PP .Vb 6 \& SWITCH: { \& if (/^abc/) { $abc = 1; last SWITCH; } \& if (/^def/) { $def = 1; last SWITCH; } \& if (/^xyz/) { $xyz = 1; last SWITCH; } \& $nothing = 1; \& } .Ve .PP There is no official \f(CW\*(C`switch\*(C'\fR statement in Perl, because there are already several ways to write the equivalent. .PP However, starting from Perl 5.8 to get switch and case one can use the Switch extension and say: .PP .Vb 1 \& use Switch; .Ve .PP after which one has switch and case. It is not as fast as it could be because it's not really part of the language (it's done using source filters) but it is available, and it's very flexible. .PP In addition to the above \s-1BLOCK\s0 construct, you could write .PP .Vb 6 \& SWITCH: { \& $abc = 1, last SWITCH if /^abc/; \& $def = 1, last SWITCH if /^def/; \& $xyz = 1, last SWITCH if /^xyz/; \& $nothing = 1; \& } .Ve .PP (That's actually not as strange as it looks once you realize that you can use loop control \*(L"operators\*(R" within an expression, That's just the normal C comma operator.) .PP or .PP .Vb 6 \& SWITCH: { \& /^abc/ && do { $abc = 1; last SWITCH; }; \& /^def/ && do { $def = 1; last SWITCH; }; \& /^xyz/ && do { $xyz = 1; last SWITCH; }; \& $nothing = 1; \& } .Ve .PP or formatted so it stands out more as a \*(L"proper\*(R" \f(CW\*(C`switch\*(C'\fR statement: .PP .Vb 5 \& SWITCH: { \& /^abc/ && do { \& $abc = 1; \& last SWITCH; \& }; .Ve .PP .Vb 4 \& /^def/ && do { \& $def = 1; \& last SWITCH; \& }; .Ve .PP .Vb 6 \& /^xyz/ && do { \& $xyz = 1; \& last SWITCH; \& }; \& $nothing = 1; \& } .Ve .PP or .PP .Vb 6 \& SWITCH: { \& /^abc/ and $abc = 1, last SWITCH; \& /^def/ and $def = 1, last SWITCH; \& /^xyz/ and $xyz = 1, last SWITCH; \& $nothing = 1; \& } .Ve .PP or even, horrors, .PP .Vb 8 \& if (/^abc/) \& { $abc = 1 } \& elsif (/^def/) \& { $def = 1 } \& elsif (/^xyz/) \& { $xyz = 1 } \& else \& { $nothing = 1 } .Ve .PP A common idiom for a \f(CW\*(C`switch\*(C'\fR statement is to use \f(CW\*(C`foreach\*(C'\fR's aliasing to make a temporary assignment to \f(CW$_\fR for convenient matching: .PP .Vb 6 \& SWITCH: for ($where) { \& /In Card Names/ && do { push @flags, '-e'; last; }; \& /Anywhere/ && do { push @flags, '-h'; last; }; \& /In Rulings/ && do { last; }; \& die "unknown value for form variable where: `$where'"; \& } .Ve .PP Another interesting approach to a switch statement is arrange for a \f(CW\*(C`do\*(C'\fR block to return the proper value: .PP .Vb 8 \& $amode = do { \& if ($flag & O_RDONLY) { "r" } # XXX: isn't this 0? \& elsif ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" } \& elsif ($flag & O_RDWR) { \& if ($flag & O_CREAT) { "w+" } \& else { ($flag & O_APPEND) ? "a+" : "r+" } \& } \& }; .Ve .PP Or .PP .Vb 5 \& print do { \& ($flags & O_WRONLY) ? "write-only" : \& ($flags & O_RDWR) ? "read-write" : \& "read-only"; \& }; .Ve .PP Or if you are certain that all the \f(CW\*(C`&&\*(C'\fR clauses are true, you can use something like this, which \*(L"switches\*(R" on the value of the \&\f(CW\*(C`HTTP_USER_AGENT\*(C'\fR environment variable. .PP .Vb 13 \& #!/usr/bin/perl \& # pick out jargon file page based on browser \& $dir = 'http://www.wins.uva.nl/~mes/jargon'; \& for ($ENV{HTTP_USER_AGENT}) { \& $page = /Mac/ && 'm/Macintrash.html' \& || /Win(dows )?NT/ && 'e/evilandrude.html' \& || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html' \& || /Linux/ && 'l/Linux.html' \& || /HP-UX/ && 'h/HP-SUX.html' \& || /SunOS/ && 's/ScumOS.html' \& || 'a/AppendixB.html'; \& } \& print "Location: $dir/$page\e015\e012\e015\e012"; .Ve .PP That kind of switch statement only works when you know the \f(CW\*(C`&&\*(C'\fR clauses will be true. If you don't, the previous \f(CW\*(C`?:\*(C'\fR example should be used. .PP You might also consider writing a hash of subroutine references instead of synthesizing a \f(CW\*(C`switch\*(C'\fR statement. .Sh "Goto" .IX Subsection "Goto" Although not for the faint of heart, Perl does support a \f(CW\*(C`goto\*(C'\fR statement. There are three forms: \f(CW\*(C`goto\*(C'\fR\-LABEL, \f(CW\*(C`goto\*(C'\fR\-EXPR, and \&\f(CW\*(C`goto\*(C'\fR\-&NAME. A loop's \s-1LABEL\s0 is not actually a valid target for a \f(CW\*(C`goto\*(C'\fR; it's just the name of the loop. .PP The \f(CW\*(C`goto\*(C'\fR\-LABEL form finds the statement labeled with \s-1LABEL\s0 and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a \f(CW\*(C`foreach\*(C'\fR loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has never felt the need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl, that is\*(--C is another matter). .PP The \f(CW\*(C`goto\*(C'\fR\-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per \s-1FORTRAN\s0, but isn't necessarily recommended if you're optimizing for maintainability: .PP .Vb 1 \& goto(("FOO", "BAR", "GLARCH")[$i]); .Ve .PP The \f(CW\*(C`goto\*(C'\fR\-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by \&\f(CW\*(C`AUTOLOAD()\*(C'\fR subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to \f(CW@_\fR in the current subroutine are propagated to the other subroutine.) After the \f(CW\*(C`goto\*(C'\fR, not even \f(CW\*(C`caller()\*(C'\fR will be able to tell that this routine was called first. .PP In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR instead of resorting to a \f(CW\*(C`goto\*(C'\fR. For certain applications, the catch and throw pair of \&\f(CW\*(C`eval{}\*(C'\fR and \fIdie()\fR for exception processing can also be a prudent approach. .Sh "PODs: Embedded Documentation" .IX Subsection "PODs: Embedded Documentation" Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this .PP .Vb 1 \& =head1 Here There Be Pods! .Ve .PP Then that text and all remaining text up through and including a line beginning with \f(CW\*(C`=cut\*(C'\fR will be ignored. The format of the intervening text is described in perlpod. .PP This allows you to intermix your source code and your documentation text freely, as in .PP .Vb 1 \& =item snazzle($) .Ve .PP .Vb 3 \& The snazzle() function will behave in the most spectacular \& form that you can possibly imagine, not even excepting \& cybernetic pyrotechnics. .Ve .PP .Vb 1 \& =cut back to the compiler, nuff of this pod stuff! .Ve .PP .Vb 4 \& sub snazzle($) { \& my $thingie = shift; \& ......... \& } .Ve .PP Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators. .PP .Vb 5 \& $a=3; \& =secret stuff \& warn "Neither POD nor CODE!?" \& =cut back \& print "got $a\en"; .Ve .PP You probably shouldn't rely upon the \f(CW\*(C`warn()\*(C'\fR being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier. .PP One may also use pod directives to quickly comment out a section of code. .Sh "Plain Old Comments (Not!)" .IX Subsection "Plain Old Comments (Not!)" Much like the C preprocessor, Perl can process line directives. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with \f(CW\*(C`eval()\*(C'\fR). The syntax for this mechanism is the same as for most C preprocessors: it matches the regular expression \&\f(CW\*(C`/^#\es*line\es+(\ed+)\es*(?:\es"([^"]+)")?\es*$/\*(C'\fR with \f(CW$1\fR being the line number for the next line, and \f(CW$2\fR being the optional filename (specified within quotes). .PP There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later. .PP Here are some examples that you should be able to type into your command shell: .PP .Vb 6 \& % perl \& # line 200 "bzzzt" \& # the `#' on the previous line must be the first char on line \& die 'foo'; \& __END__ \& foo at bzzzt line 201. .Ve .PP .Vb 5 \& % perl \& # line 200 "bzzzt" \& eval qq[\en#line 2001 ""\endie 'foo']; print $@; \& __END__ \& foo at - line 2001. .Ve .PP .Vb 4 \& % perl \& eval qq[\en#line 200 "foo bar"\endie 'foo']; print $@; \& __END__ \& foo at foo bar line 200. .Ve .PP .Vb 6 \& % perl \& # line 345 "goop" \& eval "\en#line " . __LINE__ . ' "' . __FILE__ ."\e"\endie 'foo'"; \& print $@; \& __END__ \& foo at goop line 345. .Ve