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