This is a live mirror of the Perl 5 development currently hosted at
perl 5.000
[perl5.git] / pod / perlsyn.pod
1=head1 NAME
3perlsyn - Perl syntax
7A Perl script consists of a sequence of declarations and statements.
8The only things that need to be declared in Perl are report formats
9and subroutines. See the sections below for more information on those
10declarations. All uninitialized user-created objects are assumed to
11start with a null or 0 value until they are defined by some explicit
12operation such as assignment. (Though you can get warnings about the
13use of undefined values if you like.) The sequence of statements is
14executed just once, unlike in B<sed> and B<awk> scripts, where the
15sequence of statements is executed for each input line. While this means
16that you must explicitly loop over the lines of your input file (or
17files), it also means you have much more control over which files and
18which lines you look at. (Actually, I'm lying--it is possible to do an
19implicit loop with either the B<-n> or B<-p> switch. It's just not the
20mandatory default like it is in B<sed> and B<awk>.)
22Perl is, for the most part, a free-form language. (The only
23exception to this is format declarations, for obvious reasons.) Comments
24are indicated by the "#" character, and extend to the end of the line. If
25you attempt to use C</* */> C-style comments, it will be interpreted
26either as division or pattern matching, depending on the context, and C++
27C<//> comments just look like a null regular expression, So don't do
30A declaration can be put anywhere a statement can, but has no effect on
31the execution of the primary sequence of statements--declarations all
32take effect at compile time. Typically all the declarations are put at
33the beginning or the end of the script.
35As of Perl 5, declaring a subroutine allows a subroutine name to be used
36as if it were a list operator from that point forward in the program. You
37can declare a subroutine without defining it by saying just
39 sub myname;
40 $me = myname $0 or die "can't get myname";
42Note that it functions as a list operator though, not a unary
43operator, so be careful to use C<or> instead of C<||> there.
45Subroutines declarations can also be imported by a C<use> statement.
47Also as of Perl 5, a statement sequence may contain declarations of
48lexically scoped variables, but apart from declaring a variable name,
49the declaration acts like an ordinary statement, and is elaborated within
50the sequence of statements as if it were an ordinary statement.
52=head2 Simple statements
54The only kind of simple statement is an expression evaluated for its
55side effects. Every simple statement must be terminated with a
56semicolon, unless it is the final statement in a block, in which case
57the semicolon is optional. (A semicolon is still encouraged there if the
58block takes up more than one line, since you may add another line.)
59Note that there are some operators like C<eval {}> and C<do {}> that look
60like compound statements, but aren't (they're just TERMs in an expression),
61and thus need an explicit termination
62if used as the last item in a statement.
64Any simple statement may optionally be followed by a I<SINGLE> modifier,
65just before the terminating semicolon (or block ending). The possible
66modifiers are:
68 if EXPR
69 unless EXPR
70 while EXPR
71 until EXPR
73The C<if> and C<unless> modifiers have the expected semantics,
74presuming you're a speaker of English. The C<while> and C<until>
75modifiers also have the usual "while loop" semantics (conditional
76evaluated first), except when applied to a do-BLOCK (or to the
77now-deprecated do-SUBROUTINE statement), in which case the block
78executes once before the conditional is evaluated. This is so that you
79can write loops like:
81 do {
82 $_ = <STDIN>;
83 ...
84 } until $_ eq ".\n";
86See L<perlfunc/do>. Note also that the loop control
87statements described later will I<NOT> work in this construct, since
88modifiers don't take loop labels. Sorry. You can always wrap
89another block around it to do that sort of thing.)
91=head2 Compound statements
93In Perl, a sequence of statements that defines a scope is called a block.
94Sometimes a block is delimited by the file containing it (in the case
95of a required file, or the program as a whole), and sometimes a block
96is delimited by the extent of a string (in the case of an eval).
98But generally, a block is delimited by curly brackets, also known as braces.
99We will call this syntactic construct a BLOCK.
101The following compound statements may be used to control flow:
103 if (EXPR) BLOCK
104 if (EXPR) BLOCK else BLOCK
105 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
106 LABEL while (EXPR) BLOCK
107 LABEL while (EXPR) BLOCK continue BLOCK
110 LABEL BLOCK continue BLOCK
112Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
113not statements. This means that the curly brackets are I<required>--no
114dangling statements allowed. If you want to write conditionals without
115curly brackets there are several other ways to do it. The following
116all do the same thing:
118 if (!open(FOO)) { die "Can't open $FOO: $!"; }
119 die "Can't open $FOO: $!" unless open(FOO);
120 open(FOO) or die "Can't open $FOO: $!"; # FOO or bust!
121 open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
122 # a bit exotic, that last one
124The C<if> statement is straightforward. Since BLOCKs are always
125bounded by curly brackets, there is never any ambiguity about which
126C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
127the sense of the test is reversed.
129The C<while> statement executes the block as long as the expression is
130true (does not evaluate to the null string or 0 or "0"). The LABEL is
131optional, and if present, consists of an identifier followed by a
132colon. The LABEL identifies the loop for the loop control statements
133C<next>, C<last>, and C<redo> (see below). If there is a C<continue>
134BLOCK, it is always executed just before the conditional is about to be
135evaluated again, just like the third part of a C<for> loop in C.
136Thus it can be used to increment a loop variable, even when the loop
137has been continued via the C<next> statement (which is similar to the C
138C<continue> statement).
140If the word C<while> is replaced by the word C<until>, the sense of the
141test is reversed, but the conditional is still tested before the first
144In either the C<if> or the C<while> statement, you may replace "(EXPR)"
145with a BLOCK, and the conditional is true if the value of the last
146statement in that block is true. (This feature continues to work in Perl
1475 but is deprecated. Please change any occurrences of "if BLOCK" to
148"if (do BLOCK)".)
150The C-style C<for> loop works exactly like the corresponding C<while> loop:
152 for ($i = 1; $i < 10; $i++) {
153 ...
154 }
156is the same as
158 $i = 1;
159 while ($i < 10) {
160 ...
161 } continue {
162 $i++;
163 }
165The foreach loop iterates over a normal list value and sets the
166variable VAR to be each element of the list in turn. The variable is
167implicitly local to the loop (unless declared previously with C<my>),
168and regains its former value upon exiting the loop. The C<foreach>
169keyword is actually a synonym for the C<for> keyword, so you can use
170C<foreach> for readability or C<for> for brevity. If VAR is omitted, $_
171is set to each value. If ARRAY is an actual array (as opposed to an
172expression returning a list value), you can modify each element of the
173array by modifying VAR inside the loop. Examples:
175 for (@ary) { s/foo/bar/; }
177 foreach $elem (@elements) {
178 $elem *= 2;
179 }
181 for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
182 print $_, "\n"; sleep(1);
183 }
185 for (1..15) { print "Merry Christmas\n"; }
187 foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
188 print "Item: $item\n";
189 }
191A BLOCK by itself (labeled or not) is semantically equivalent to a loop
192that executes once. Thus you can use any of the loop control
193statements in it to leave or restart the block. The C<continue> block
194is optional. This construct is particularly nice for doing case
197 SWITCH: {
198 if (/^abc/) { $abc = 1; last SWITCH; }
199 if (/^def/) { $def = 1; last SWITCH; }
200 if (/^xyz/) { $xyz = 1; last SWITCH; }
201 $nothing = 1;
202 }
204There is no official switch statement in Perl, because there are
205already several ways to write the equivalent. In addition to the
206above, you could write
208 SWITCH: {
209 $abc = 1, last SWITCH if /^abc/;
210 $def = 1, last SWITCH if /^def/;
211 $xyz = 1, last SWITCH if /^xyz/;
212 $nothing = 1;
213 }
215(That's actually not as strange as it looks one you realize that you can
216use loop control "operators" within an expression, That's just the normal
217C comma operator.)
221 SWITCH: {
222 /^abc/ && do { $abc = 1; last SWITCH; };
223 /^def/ && do { $def = 1; last SWITCH; };
224 /^xyz/ && do { $xyz = 1; last SWITCH; };
225 $nothing = 1;
226 }
228or formatted so it stands out more as a "proper" switch statement:
230 SWITCH: {
231 /^abc/ && do {
232 $abc = 1;
233 last SWITCH;
234 };
236 /^def/ && do {
237 $def = 1;
238 last SWITCH;
239 };
241 /^xyz/ && do {
242 $xyz = 1;
243 last SWITCH;
244 };
245 $nothing = 1;
246 }
250 SWITCH: {
251 /^abc/ and $abc = 1, last SWITCH;
252 /^def/ and $def = 1, last SWITCH;
253 /^xyz/ and $xyz = 1, last SWITCH;
254 $nothing = 1;
255 }
257or even, horrors,
259 if (/^abc/)
260 { $abc = 1 }
261 elsif (/^def/)
262 { $def = 1 }
263 elsif (/^xyz/)
264 { $xyz = 1 }
265 else
266 { $nothing = 1 }