Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / amd64 / man / man1 / perlsyn.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLSYN 1"
132.TH PERLSYN 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134.IX Xref "syntax"
135perlsyn \- Perl syntax
136.SH "DESCRIPTION"
137.IX Header "DESCRIPTION"
138A Perl program consists of a sequence of declarations and statements
139which run from the top to the bottom. Loops, subroutines and other
140control structures allow you to jump around within the code.
141.PP
142Perl is a \fBfree-form\fR language, you can format and indent it however
143you like. Whitespace mostly serves to separate tokens, unlike
144languages like Python where it is an important part of the syntax.
145.PP
146Many of Perl's syntactic elements are \fBoptional\fR. Rather than
147requiring you to put parentheses around every function call and
148declare every variable, you can often leave such explicit elements off
149and Perl will figure out what you meant. This is known as \fBDo What I
150Mean\fR, abbreviated \fB\s-1DWIM\s0\fR. It allows programmers to be \fBlazy\fR and to
151code in a style with which they are comfortable.
152.PP
153Perl \fBborrows syntax\fR and concepts from many languages: awk, sed, C,
154Bourne Shell, Smalltalk, Lisp and even English. Other
155languages have borrowed syntax from Perl, particularly its regular
156expression extensions. So if you have programmed in another language
157you will see familiar pieces in Perl. They often work the same, but
158see perltrap for information about how they differ.
159.Sh "Declarations"
160.IX Xref "declaration undef undefined uninitialized"
161.IX Subsection "Declarations"
162The only things you need to declare in Perl are report formats and
163subroutines (and sometimes not even subroutines). A variable holds
164the undefined value (\f(CW\*(C`undef\*(C'\fR) until it has been assigned a defined
165value, which is anything other than \f(CW\*(C`undef\*(C'\fR. When used as a number,
166\&\f(CW\*(C`undef\*(C'\fR is treated as \f(CW0\fR; when used as a string, it is treated as
167the empty string, \f(CW""\fR; and when used as a reference that isn't being
168assigned to, it is treated as an error. If you enable warnings,
169you'll be notified of an uninitialized value whenever you treat
170\&\f(CW\*(C`undef\*(C'\fR as a string or a number. Well, usually. Boolean contexts,
171such as:
172.PP
173.Vb 2
174\& my $a;
175\& if ($a) {}
176.Ve
177.PP
178are exempt from warnings (because they care about truth rather than
179definedness). Operators such as \f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR,
180\&\f(CW\*(C`\-=\*(C'\fR, and \f(CW\*(C`.=\*(C'\fR, that operate on undefined left values such as:
181.PP
182.Vb 2
183\& my $a;
184\& $a++;
185.Ve
186.PP
187are also always exempt from such warnings.
188.PP
189A declaration can be put anywhere a statement can, but has no effect on
190the execution of the primary sequence of statements\*(--declarations all
191take effect at compile time. Typically all the declarations are put at
192the beginning or the end of the script. However, if you're using
193lexically-scoped private variables created with \f(CW\*(C`my()\*(C'\fR, you'll
194have to make sure
195your format or subroutine definition is within the same block scope
196as the my if you expect to be able to access those private variables.
197.PP
198Declaring a subroutine allows a subroutine name to be used as if it were a
199list operator from that point forward in the program. You can declare a
200subroutine without defining it by saying \f(CW\*(C`sub name\*(C'\fR, thus:
201.IX Xref "subroutine, declaration"
202.PP
203.Vb 2
204\& sub myname;
205\& $me = myname $0 or die "can't get myname";
206.Ve
207.PP
208Note that \fImyname()\fR functions as a list operator, not as a unary operator;
209so be careful to use \f(CW\*(C`or\*(C'\fR instead of \f(CW\*(C`||\*(C'\fR in this case. However, if
210you were to declare the subroutine as \f(CW\*(C`sub myname ($)\*(C'\fR, then
211\&\f(CW\*(C`myname\*(C'\fR would function as a unary operator, so either \f(CW\*(C`or\*(C'\fR or
212\&\f(CW\*(C`||\*(C'\fR would work.
213.PP
214Subroutines declarations can also be loaded up with the \f(CW\*(C`require\*(C'\fR statement
215or both loaded and imported into your namespace with a \f(CW\*(C`use\*(C'\fR statement.
216See perlmod for details on this.
217.PP
218A statement sequence may contain declarations of lexically-scoped
219variables, but apart from declaring a variable name, the declaration acts
220like an ordinary statement, and is elaborated within the sequence of
221statements as if it were an ordinary statement. That means it actually
222has both compile-time and run-time effects.
223.Sh "Comments"
224.IX Xref "comment #"
225.IX Subsection "Comments"
226Text from a \f(CW"#"\fR character until the end of the line is a comment,
227and is ignored. Exceptions include \f(CW"#"\fR inside a string or regular
228expression.
229.Sh "Simple Statements"
230.IX Xref "statement semicolon expression ;"
231.IX Subsection "Simple Statements"
232The only kind of simple statement is an expression evaluated for its
233side effects. Every simple statement must be terminated with a
234semicolon, unless it is the final statement in a block, in which case
235the semicolon is optional. (A semicolon is still encouraged if the
236block takes up more than one line, because you may eventually add
237another line.) Note that there are some operators like \f(CW\*(C`eval {}\*(C'\fR and
238\&\f(CW\*(C`do {}\*(C'\fR that look like compound statements, but aren't (they're just
239TERMs in an expression), and thus need an explicit termination if used
240as the last item in a statement.
241.Sh "Truth and Falsehood"
242.IX Xref "truth falsehood true false ! not negation 0"
243.IX Subsection "Truth and Falsehood"
244The number 0, the strings \f(CW'0'\fR and \f(CW''\fR, the empty list \f(CW\*(C`()\*(C'\fR, and
245\&\f(CW\*(C`undef\*(C'\fR are all false in a boolean context. All other values are true.
246Negation of a true value by \f(CW\*(C`!\*(C'\fR or \f(CW\*(C`not\*(C'\fR returns a special false value.
247When evaluated as a string it is treated as \f(CW''\fR, but as a number, it
248is treated as 0.
249.Sh "Statement Modifiers"
250.IX Xref "statement modifier modifier if unless while until foreach for"
251.IX Subsection "Statement Modifiers"
252Any simple statement may optionally be followed by a \fI\s-1SINGLE\s0\fR modifier,
253just before the terminating semicolon (or block ending). The possible
254modifiers are:
255.PP
256.Vb 5
257\& if EXPR
258\& unless EXPR
259\& while EXPR
260\& until EXPR
261\& foreach LIST
262.Ve
263.PP
264The \f(CW\*(C`EXPR\*(C'\fR following the modifier is referred to as the \*(L"condition\*(R".
265Its truth or falsehood determines how the modifier will behave.
266.PP
267\&\f(CW\*(C`if\*(C'\fR executes the statement once \fIif\fR and only if the condition is
268true. \f(CW\*(C`unless\*(C'\fR is the opposite, it executes the statement \fIunless\fR
269the condition is true (i.e., if the condition is false).
270.PP
271.Vb 2
272\& print "Basset hounds got long ears" if length $ear >= 10;
273\& go_outside() and play() unless $is_raining;
274.Ve
275.PP
276The \f(CW\*(C`foreach\*(C'\fR modifier is an iterator: it executes the statement once
277for each item in the \s-1LIST\s0 (with \f(CW$_\fR aliased to each item in turn).
278.PP
279.Vb 1
280\& print "Hello $_!\en" foreach qw(world Dolly nurse);
281.Ve
282.PP
283\&\f(CW\*(C`while\*(C'\fR repeats the statement \fIwhile\fR the condition is true.
284\&\f(CW\*(C`until\*(C'\fR does the opposite, it repeats the statement \fIuntil\fR the
285condition is true (or while the condition is false):
286.PP
287.Vb 3
288\& # Both of these count from 0 to 10.
289\& print $i++ while $i <= 10;
290\& print $j++ until $j > 10;
291.Ve
292.PP
293The \f(CW\*(C`while\*(C'\fR and \f(CW\*(C`until\*(C'\fR modifiers have the usual "\f(CW\*(C`while\*(C'\fR loop"
294semantics (conditional evaluated first), except when applied to a
295\&\f(CW\*(C`do\*(C'\fR\-BLOCK (or to the deprecated \f(CW\*(C`do\*(C'\fR\-SUBROUTINE statement), in
296which case the block executes once before the conditional is
297evaluated. This is so that you can write loops like:
298.PP
299.Vb 4
300\& do {
301\& $line = <STDIN>;
302\& ...
303\& } until $line eq ".\en";
304.Ve
305.PP
306See \*(L"do\*(R" in perlfunc. Note also that the loop control statements described
307later will \fI\s-1NOT\s0\fR work in this construct, because modifiers don't take
308loop labels. Sorry. You can always put another block inside of it
309(for \f(CW\*(C`next\*(C'\fR) or around it (for \f(CW\*(C`last\*(C'\fR) to do that sort of thing.
310For \f(CW\*(C`next\*(C'\fR, just double the braces:
311.IX Xref "next last redo"
312.PP
313.Vb 4
314\& do {{
315\& next if $x == $y;
316\& # do something here
317\& }} until $x++ > $z;
318.Ve
319.PP
320For \f(CW\*(C`last\*(C'\fR, you have to be more elaborate:
321.IX Xref "last"
322.PP
323.Vb 6
324\& LOOP: {
325\& do {
326\& last if $x = $y**2;
327\& # do something here
328\& } while $x++ <= $z;
329\& }
330.Ve
331.PP
332\&\fB\s-1NOTE:\s0\fR The behaviour of a \f(CW\*(C`my\*(C'\fR statement modified with a statement
333modifier conditional or loop construct (e.g. \f(CW\*(C`my $x if ...\*(C'\fR) is
334\&\fBundefined\fR. The value of the \f(CW\*(C`my\*(C'\fR variable may be \f(CW\*(C`undef\*(C'\fR, any
335previously assigned value, or possibly anything else. Don't rely on
336it. Future versions of perl might do something different from the
337version of perl you try it out on. Here be dragons.
338.IX Xref "my"
339.Sh "Compound Statements"
340.IX Xref "statement, compound block bracket, curly curly bracket brace { } if unless while until foreach for continue"
341.IX Subsection "Compound Statements"
342In Perl, a sequence of statements that defines a scope is called a block.
343Sometimes a block is delimited by the file containing it (in the case
344of a required file, or the program as a whole), and sometimes a block
345is delimited by the extent of a string (in the case of an eval).
346.PP
347But generally, a block is delimited by curly brackets, also known as braces.
348We will call this syntactic construct a \s-1BLOCK\s0.
349.PP
350The following compound statements may be used to control flow:
351.PP
352.Vb 11
353\& if (EXPR) BLOCK
354\& if (EXPR) BLOCK else BLOCK
355\& if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
356\& LABEL while (EXPR) BLOCK
357\& LABEL while (EXPR) BLOCK continue BLOCK
358\& LABEL until (EXPR) BLOCK
359\& LABEL until (EXPR) BLOCK continue BLOCK
360\& LABEL for (EXPR; EXPR; EXPR) BLOCK
361\& LABEL foreach VAR (LIST) BLOCK
362\& LABEL foreach VAR (LIST) BLOCK continue BLOCK
363\& LABEL BLOCK continue BLOCK
364.Ve
365.PP
366Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
367not statements. This means that the curly brackets are \fIrequired\fR\-\-no
368dangling statements allowed. If you want to write conditionals without
369curly brackets there are several other ways to do it. The following
370all do the same thing:
371.PP
372.Vb 5
373\& if (!open(FOO)) { die "Can't open $FOO: $!"; }
374\& die "Can't open $FOO: $!" unless open(FOO);
375\& open(FOO) or die "Can't open $FOO: $!"; # FOO or bust!
376\& open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
377\& # a bit exotic, that last one
378.Ve
379.PP
380The \f(CW\*(C`if\*(C'\fR statement is straightforward. Because BLOCKs are always
381bounded by curly brackets, there is never any ambiguity about which
382\&\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,
383the sense of the test is reversed.
384.PP
385The \f(CW\*(C`while\*(C'\fR statement executes the block as long as the expression is
386true (does not evaluate to the null string \f(CW""\fR or \f(CW0\fR or \f(CW"0"\fR).
387The \f(CW\*(C`until\*(C'\fR statement executes the block as long as the expression is
388false.
389The \s-1LABEL\s0 is optional, and if present, consists of an identifier followed
390by a colon. The \s-1LABEL\s0 identifies the loop for the loop control
391statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, and \f(CW\*(C`redo\*(C'\fR.
392If the \s-1LABEL\s0 is omitted, the loop control statement
393refers to the innermost enclosing loop. This may include dynamically
394looking back your call-stack at run time to find the \s-1LABEL\s0. Such
395desperate behavior triggers a warning if you use the \f(CW\*(C`use warnings\*(C'\fR
396pragma or the \fB\-w\fR flag.
397.PP
398If there is a \f(CW\*(C`continue\*(C'\fR \s-1BLOCK\s0, it is always executed just before the
399conditional is about to be evaluated again. Thus it can be used to
400increment a loop variable, even when the loop has been continued via
401the \f(CW\*(C`next\*(C'\fR statement.
402.Sh "Loop Control"
403.IX Xref "loop control loop, control next last redo continue"
404.IX Subsection "Loop Control"
405The \f(CW\*(C`next\*(C'\fR command starts the next iteration of the loop:
406.PP
407.Vb 4
408\& LINE: while (<STDIN>) {
409\& next LINE if /^#/; # discard comments
410\& ...
411\& }
412.Ve
413.PP
414The \f(CW\*(C`last\*(C'\fR command immediately exits the loop in question. The
415\&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed:
416.PP
417.Vb 4
418\& LINE: while (<STDIN>) {
419\& last LINE if /^$/; # exit when done with header
420\& ...
421\& }
422.Ve
423.PP
424The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without evaluating the
425conditional again. The \f(CW\*(C`continue\*(C'\fR block, if any, is \fInot\fR executed.
426This command is normally used by programs that want to lie to themselves
427about what was just input.
428.PP
429For example, when processing a file like \fI/etc/termcap\fR.
430If your input lines might end in backslashes to indicate continuation, you
431want to skip ahead and get the next record.
432.PP
433.Vb 8
434\& while (<>) {
435\& chomp;
436\& if (s/\e\e$//) {
437\& $_ .= <>;
438\& redo unless eof();
439\& }
440\& # now process $_
441\& }
442.Ve
443.PP
444which is Perl short-hand for the more explicitly written version:
445.PP
446.Vb 8
447\& LINE: while (defined($line = <ARGV>)) {
448\& chomp($line);
449\& if ($line =~ s/\e\e$//) {
450\& $line .= <ARGV>;
451\& redo LINE unless eof(); # not eof(ARGV)!
452\& }
453\& # now process $line
454\& }
455.Ve
456.PP
457Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the above code, it would
458get executed only on lines discarded by the regex (since redo skips the
459continue block). A continue block is often used to reset line counters
460or \f(CW\*(C`?pat?\*(C'\fR one-time matches:
461.PP
462.Vb 10
463\& # inspired by :1,$g/fred/s//WILMA/
464\& while (<>) {
465\& ?(fred)? && s//WILMA $1 WILMA/;
466\& ?(barney)? && s//BETTY $1 BETTY/;
467\& ?(homer)? && s//MARGE $1 MARGE/;
468\& } continue {
469\& print "$ARGV $.: $_";
470\& close ARGV if eof(); # reset $.
471\& reset if eof(); # reset ?pat?
472\& }
473.Ve
474.PP
475If the word \f(CW\*(C`while\*(C'\fR is replaced by the word \f(CW\*(C`until\*(C'\fR, the sense of the
476test is reversed, but the conditional is still tested before the first
477iteration.
478.PP
479The loop control statements don't work in an \f(CW\*(C`if\*(C'\fR or \f(CW\*(C`unless\*(C'\fR, since
480they aren't loops. You can double the braces to make them such, though.
481.PP
482.Vb 5
483\& if (/pattern/) {{
484\& last if /fred/;
485\& next if /barney/; # same effect as "last", but doesn't document as well
486\& # do something here
487\& }}
488.Ve
489.PP
490This is caused by the fact that a block by itself acts as a loop that
491executes once, see \*(L"Basic BLOCKs and Switch Statements\*(R".
492.PP
493The form \f(CW\*(C`while/if BLOCK BLOCK\*(C'\fR, available in Perl 4, is no longer
494available. Replace any occurrence of \f(CW\*(C`if BLOCK\*(C'\fR by \f(CW\*(C`if (do BLOCK)\*(C'\fR.
495.Sh "For Loops"
496.IX Xref "for foreach"
497.IX Subsection "For Loops"
498Perl's C\-style \f(CW\*(C`for\*(C'\fR loop works like the corresponding \f(CW\*(C`while\*(C'\fR loop;
499that means that this:
500.PP
501.Vb 3
502\& for ($i = 1; $i < 10; $i++) {
503\& ...
504\& }
505.Ve
506.PP
507is the same as this:
508.PP
509.Vb 6
510\& $i = 1;
511\& while ($i < 10) {
512\& ...
513\& } continue {
514\& $i++;
515\& }
516.Ve
517.PP
518There is one minor difference: if variables are declared with \f(CW\*(C`my\*(C'\fR
519in the initialization section of the \f(CW\*(C`for\*(C'\fR, the lexical scope of
520those variables is exactly the \f(CW\*(C`for\*(C'\fR loop (the body of the loop
521and the control sections).
522.IX Xref "my"
523.PP
524Besides the normal array index looping, \f(CW\*(C`for\*(C'\fR can lend itself
525to many other interesting applications. Here's one that avoids the
526problem you get into if you explicitly test for end-of-file on
527an interactive file descriptor causing your program to appear to
528hang.
529.IX Xref "eof end-of-file end of file"
530.PP
531.Vb 5
532\& $on_a_tty = -t STDIN && -t STDOUT;
533\& sub prompt { print "yes? " if $on_a_tty }
534\& for ( prompt(); <STDIN>; prompt() ) {
535\& # do something
536\& }
537.Ve
538.PP
539Using \f(CW\*(C`readline\*(C'\fR (or the operator form, \f(CW\*(C`<EXPR>\*(C'\fR) as the
540conditional of a \f(CW\*(C`for\*(C'\fR loop is shorthand for the following. This
541behaviour is the same as a \f(CW\*(C`while\*(C'\fR loop conditional.
542.IX Xref "readline <>"
543.PP
544.Vb 3
545\& for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
546\& # do something
547\& }
548.Ve
549.Sh "Foreach Loops"
550.IX Xref "for foreach"
551.IX Subsection "Foreach Loops"
552The \f(CW\*(C`foreach\*(C'\fR loop iterates over a normal list value and sets the
553variable \s-1VAR\s0 to be each element of the list in turn. If the variable
554is preceded with the keyword \f(CW\*(C`my\*(C'\fR, then it is lexically scoped, and
555is therefore visible only within the loop. Otherwise, the variable is
556implicitly local to the loop and regains its former value upon exiting
557the loop. If the variable was previously declared with \f(CW\*(C`my\*(C'\fR, it uses
558that variable instead of the global one, but it's still localized to
559the loop. This implicit localisation occurs \fIonly\fR in a \f(CW\*(C`foreach\*(C'\fR
560loop.
561.IX Xref "my local"
562.PP
563The \f(CW\*(C`foreach\*(C'\fR keyword is actually a synonym for the \f(CW\*(C`for\*(C'\fR keyword, so
564you can use \f(CW\*(C`foreach\*(C'\fR for readability or \f(CW\*(C`for\*(C'\fR for brevity. (Or because
565the Bourne shell is more familiar to you than \fIcsh\fR, so writing \f(CW\*(C`for\*(C'\fR
566comes more naturally.) If \s-1VAR\s0 is omitted, \f(CW$_\fR is set to each value.
567.IX Xref "$_"
568.PP
569If any element of \s-1LIST\s0 is an lvalue, you can modify it by modifying
570\&\s-1VAR\s0 inside the loop. Conversely, if any element of \s-1LIST\s0 is \s-1NOT\s0 an
571lvalue, any attempt to modify that element will fail. In other words,
572the \f(CW\*(C`foreach\*(C'\fR loop index variable is an implicit alias for each item
573in the list that you're looping over.
574.IX Xref "alias"
575.PP
576If any part of \s-1LIST\s0 is an array, \f(CW\*(C`foreach\*(C'\fR will get very confused if
577you add or remove elements within the loop body, for example with
578\&\f(CW\*(C`splice\*(C'\fR. So don't do that.
579.IX Xref "splice"
580.PP
581\&\f(CW\*(C`foreach\*(C'\fR probably won't do what you expect if \s-1VAR\s0 is a tied or other
582special variable. Don't do that either.
583.PP
584Examples:
585.PP
586.Vb 1
587\& for (@ary) { s/foo/bar/ }
588.Ve
589.PP
590.Vb 3
591\& for my $elem (@elements) {
592\& $elem *= 2;
593\& }
594.Ve
595.PP
596.Vb 3
597\& for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
598\& print $count, "\en"; sleep(1);
599\& }
600.Ve
601.PP
602.Vb 1
603\& for (1..15) { print "Merry Christmas\en"; }
604.Ve
605.PP
606.Vb 3
607\& foreach $item (split(/:[\e\e\en:]*/, $ENV{TERMCAP})) {
608\& print "Item: $item\en";
609\& }
610.Ve
611.PP
612Here's how a C programmer might code up a particular algorithm in Perl:
613.PP
614.Vb 9
615\& for (my $i = 0; $i < @ary1; $i++) {
616\& for (my $j = 0; $j < @ary2; $j++) {
617\& if ($ary1[$i] > $ary2[$j]) {
618\& last; # can't go to outer :-(
619\& }
620\& $ary1[$i] += $ary2[$j];
621\& }
622\& # this is where that last takes me
623\& }
624.Ve
625.PP
626Whereas here's how a Perl programmer more comfortable with the idiom might
627do it:
628.PP
629.Vb 6
630\& OUTER: for my $wid (@ary1) {
631\& INNER: for my $jet (@ary2) {
632\& next OUTER if $wid > $jet;
633\& $wid += $jet;
634\& }
635\& }
636.Ve
637.PP
638See how much easier this is? It's cleaner, safer, and faster. It's
639cleaner because it's less noisy. It's safer because if code gets added
640between the inner and outer loops later on, the new code won't be
641accidentally executed. The \f(CW\*(C`next\*(C'\fR explicitly iterates the other loop
642rather than merely terminating the inner one. And it's faster because
643Perl executes a \f(CW\*(C`foreach\*(C'\fR statement more rapidly than it would the
644equivalent \f(CW\*(C`for\*(C'\fR loop.
645.Sh "Basic BLOCKs and Switch Statements"
646.IX Xref "switch block case"
647.IX Subsection "Basic BLOCKs and Switch Statements"
648A \s-1BLOCK\s0 by itself (labeled or not) is semantically equivalent to a
649loop that executes once. Thus you can use any of the loop control
650statements in it to leave or restart the block. (Note that this is
651\&\fI\s-1NOT\s0\fR true in \f(CW\*(C`eval{}\*(C'\fR, \f(CW\*(C`sub{}\*(C'\fR, or contrary to popular belief
652\&\f(CW\*(C`do{}\*(C'\fR blocks, which do \fI\s-1NOT\s0\fR count as loops.) The \f(CW\*(C`continue\*(C'\fR
653block is optional.
654.PP
655The \s-1BLOCK\s0 construct is particularly nice for doing case
656structures.
657.PP
658.Vb 6
659\& SWITCH: {
660\& if (/^abc/) { $abc = 1; last SWITCH; }
661\& if (/^def/) { $def = 1; last SWITCH; }
662\& if (/^xyz/) { $xyz = 1; last SWITCH; }
663\& $nothing = 1;
664\& }
665.Ve
666.PP
667There is no official \f(CW\*(C`switch\*(C'\fR statement in Perl, because there are
668already several ways to write the equivalent.
669.PP
670However, starting from Perl 5.8 to get switch and case one can use
671the Switch extension and say:
672.PP
673.Vb 1
674\& use Switch;
675.Ve
676.PP
677after which one has switch and case. It is not as fast as it could be
678because it's not really part of the language (it's done using source
679filters) but it is available, and it's very flexible.
680.PP
681In addition to the above \s-1BLOCK\s0 construct, you could write
682.PP
683.Vb 6
684\& SWITCH: {
685\& $abc = 1, last SWITCH if /^abc/;
686\& $def = 1, last SWITCH if /^def/;
687\& $xyz = 1, last SWITCH if /^xyz/;
688\& $nothing = 1;
689\& }
690.Ve
691.PP
692(That's actually not as strange as it looks once you realize that you can
693use loop control \*(L"operators\*(R" within an expression. That's just the binary
694comma operator in scalar context. See \*(L"Comma Operator\*(R" in perlop.)
695.PP
696or
697.PP
698.Vb 6
699\& SWITCH: {
700\& /^abc/ && do { $abc = 1; last SWITCH; };
701\& /^def/ && do { $def = 1; last SWITCH; };
702\& /^xyz/ && do { $xyz = 1; last SWITCH; };
703\& $nothing = 1;
704\& }
705.Ve
706.PP
707or formatted so it stands out more as a \*(L"proper\*(R" \f(CW\*(C`switch\*(C'\fR statement:
708.PP
709.Vb 5
710\& SWITCH: {
711\& /^abc/ && do {
712\& $abc = 1;
713\& last SWITCH;
714\& };
715.Ve
716.PP
717.Vb 4
718\& /^def/ && do {
719\& $def = 1;
720\& last SWITCH;
721\& };
722.Ve
723.PP
724.Vb 6
725\& /^xyz/ && do {
726\& $xyz = 1;
727\& last SWITCH;
728\& };
729\& $nothing = 1;
730\& }
731.Ve
732.PP
733or
734.PP
735.Vb 6
736\& SWITCH: {
737\& /^abc/ and $abc = 1, last SWITCH;
738\& /^def/ and $def = 1, last SWITCH;
739\& /^xyz/ and $xyz = 1, last SWITCH;
740\& $nothing = 1;
741\& }
742.Ve
743.PP
744or even, horrors,
745.PP
746.Vb 8
747\& if (/^abc/)
748\& { $abc = 1 }
749\& elsif (/^def/)
750\& { $def = 1 }
751\& elsif (/^xyz/)
752\& { $xyz = 1 }
753\& else
754\& { $nothing = 1 }
755.Ve
756.PP
757A common idiom for a \f(CW\*(C`switch\*(C'\fR statement is to use \f(CW\*(C`foreach\*(C'\fR's aliasing to make
758a temporary assignment to \f(CW$_\fR for convenient matching:
759.PP
760.Vb 6
761\& SWITCH: for ($where) {
762\& /In Card Names/ && do { push @flags, '-e'; last; };
763\& /Anywhere/ && do { push @flags, '-h'; last; };
764\& /In Rulings/ && do { last; };
765\& die "unknown value for form variable where: `$where'";
766\& }
767.Ve
768.PP
769Another interesting approach to a switch statement is arrange
770for a \f(CW\*(C`do\*(C'\fR block to return the proper value:
771.PP
772.Vb 8
773\& $amode = do {
774\& if ($flag & O_RDONLY) { "r" } # XXX: isn't this 0?
775\& elsif ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
776\& elsif ($flag & O_RDWR) {
777\& if ($flag & O_CREAT) { "w+" }
778\& else { ($flag & O_APPEND) ? "a+" : "r+" }
779\& }
780\& };
781.Ve
782.PP
783Or
784.PP
785.Vb 5
786\& print do {
787\& ($flags & O_WRONLY) ? "write-only" :
788\& ($flags & O_RDWR) ? "read-write" :
789\& "read-only";
790\& };
791.Ve
792.PP
793Or if you are certain that all the \f(CW\*(C`&&\*(C'\fR clauses are true, you can use
794something like this, which \*(L"switches\*(R" on the value of the
795\&\f(CW\*(C`HTTP_USER_AGENT\*(C'\fR environment variable.
796.PP
797.Vb 13
798\& #!/usr/bin/perl
799\& # pick out jargon file page based on browser
800\& $dir = 'http://www.wins.uva.nl/~mes/jargon';
801\& for ($ENV{HTTP_USER_AGENT}) {
802\& $page = /Mac/ && 'm/Macintrash.html'
803\& || /Win(dows )?NT/ && 'e/evilandrude.html'
804\& || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html'
805\& || /Linux/ && 'l/Linux.html'
806\& || /HP-UX/ && 'h/HP-SUX.html'
807\& || /SunOS/ && 's/ScumOS.html'
808\& || 'a/AppendixB.html';
809\& }
810\& print "Location: $dir/$page\e015\e012\e015\e012";
811.Ve
812.PP
813That kind of switch statement only works when you know the \f(CW\*(C`&&\*(C'\fR clauses
814will be true. If you don't, the previous \f(CW\*(C`?:\*(C'\fR example should be used.
815.PP
816You might also consider writing a hash of subroutine references
817instead of synthesizing a \f(CW\*(C`switch\*(C'\fR statement.
818.Sh "Goto"
819.IX Xref "goto"
820.IX Subsection "Goto"
821Although not for the faint of heart, Perl does support a \f(CW\*(C`goto\*(C'\fR
822statement. There are three forms: \f(CW\*(C`goto\*(C'\fR\-LABEL, \f(CW\*(C`goto\*(C'\fR\-EXPR, and
823\&\f(CW\*(C`goto\*(C'\fR\-&NAME. A loop's \s-1LABEL\s0 is not actually a valid target for
824a \f(CW\*(C`goto\*(C'\fR; it's just the name of the loop.
825.PP
826The \f(CW\*(C`goto\*(C'\fR\-LABEL form finds the statement labeled with \s-1LABEL\s0 and resumes
827execution there. It may not be used to go into any construct that
828requires initialization, such as a subroutine or a \f(CW\*(C`foreach\*(C'\fR loop. It
829also can't be used to go into a construct that is optimized away. It
830can be used to go almost anywhere else within the dynamic scope,
831including out of subroutines, but it's usually better to use some other
832construct such as \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has never felt the
833need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl, that is\*(--C is another matter).
834.PP
835The \f(CW\*(C`goto\*(C'\fR\-EXPR form expects a label name, whose scope will be resolved
836dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per \s-1FORTRAN\s0, but isn't
837necessarily recommended if you're optimizing for maintainability:
838.PP
839.Vb 1
840\& goto(("FOO", "BAR", "GLARCH")[$i]);
841.Ve
842.PP
843The \f(CW\*(C`goto\*(C'\fR\-&NAME form is highly magical, and substitutes a call to the
844named subroutine for the currently running subroutine. This is used by
845\&\f(CW\*(C`AUTOLOAD()\*(C'\fR subroutines that wish to load another subroutine and then
846pretend that the other subroutine had been called in the first place
847(except that any modifications to \f(CW@_\fR in the current subroutine are
848propagated to the other subroutine.) After the \f(CW\*(C`goto\*(C'\fR, not even \f(CW\*(C`caller()\*(C'\fR
849will be able to tell that this routine was called first.
850.PP
851In almost all cases like this, it's usually a far, far better idea to use the
852structured 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
853resorting to a \f(CW\*(C`goto\*(C'\fR. For certain applications, the catch and throw pair of
854\&\f(CW\*(C`eval{}\*(C'\fR and \fIdie()\fR for exception processing can also be a prudent approach.
855.Sh "PODs: Embedded Documentation"
856.IX Xref "POD documentation"
857.IX Subsection "PODs: Embedded Documentation"
858Perl has a mechanism for intermixing documentation with source code.
859While it's expecting the beginning of a new statement, if the compiler
860encounters a line that begins with an equal sign and a word, like this
861.PP
862.Vb 1
863\& =head1 Here There Be Pods!
864.Ve
865.PP
866Then that text and all remaining text up through and including a line
867beginning with \f(CW\*(C`=cut\*(C'\fR will be ignored. The format of the intervening
868text is described in perlpod.
869.PP
870This allows you to intermix your source code
871and your documentation text freely, as in
872.PP
873.Vb 1
874\& =item snazzle($)
875.Ve
876.PP
877.Vb 3
878\& The snazzle() function will behave in the most spectacular
879\& form that you can possibly imagine, not even excepting
880\& cybernetic pyrotechnics.
881.Ve
882.PP
883.Vb 1
884\& =cut back to the compiler, nuff of this pod stuff!
885.Ve
886.PP
887.Vb 4
888\& sub snazzle($) {
889\& my $thingie = shift;
890\& .........
891\& }
892.Ve
893.PP
894Note that pod translators should look at only paragraphs beginning
895with a pod directive (it makes parsing easier), whereas the compiler
896actually knows to look for pod escapes even in the middle of a
897paragraph. This means that the following secret stuff will be
898ignored by both the compiler and the translators.
899.PP
900.Vb 5
901\& $a=3;
902\& =secret stuff
903\& warn "Neither POD nor CODE!?"
904\& =cut back
905\& print "got $a\en";
906.Ve
907.PP
908You probably shouldn't rely upon the \f(CW\*(C`warn()\*(C'\fR being podded out forever.
909Not all pod translators are well-behaved in this regard, and perhaps
910the compiler will become pickier.
911.PP
912One may also use pod directives to quickly comment out a section
913of code.
914.Sh "Plain Old Comments (Not!)"
915.IX Xref "comment line # preprocessor eval"
916.IX Subsection "Plain Old Comments (Not!)"
917Perl can process line directives, much like the C preprocessor. Using
918this, one can control Perl's idea of filenames and line numbers in
919error or warning messages (especially for strings that are processed
920with \f(CW\*(C`eval()\*(C'\fR). The syntax for this mechanism is the same as for most
921C preprocessors: it matches the regular expression
922.PP
923.Vb 5
924\& # example: '# line 42 "new_filename.plx"'
925\& /^\e# \es*
926\& line \es+ (\ed+) \es*
927\& (?:\es("?)([^"]+)\e2)? \es*
928\& $/x
929.Ve
930.PP
931with \f(CW$1\fR being the line number for the next line, and \f(CW$3\fR being
932the optional filename (specified with or without quotes).
933.PP
934There is a fairly obvious gotcha included with the line directive:
935Debuggers and profilers will only show the last source line to appear
936at a particular line number in a given file. Care should be taken not
937to cause line number collisions in code you'd like to debug later.
938.PP
939Here are some examples that you should be able to type into your command
940shell:
941.PP
942.Vb 6
943\& % perl
944\& # line 200 "bzzzt"
945\& # the `#' on the previous line must be the first char on line
946\& die 'foo';
947\& __END__
948\& foo at bzzzt line 201.
949.Ve
950.PP
951.Vb 5
952\& % perl
953\& # line 200 "bzzzt"
954\& eval qq[\en#line 2001 ""\endie 'foo']; print $@;
955\& __END__
956\& foo at - line 2001.
957.Ve
958.PP
959.Vb 4
960\& % perl
961\& eval qq[\en#line 200 "foo bar"\endie 'foo']; print $@;
962\& __END__
963\& foo at foo bar line 200.
964.Ve
965.PP
966.Vb 6
967\& % perl
968\& # line 345 "goop"
969\& eval "\en#line " . __LINE__ . ' "' . __FILE__ ."\e"\endie 'foo'";
970\& print $@;
971\& __END__
972\& foo at goop line 345.
973.Ve