Penguin
Annotated edit history of perlsyn(1) version 1, including all changes. View license author blame.
Rev Author # Line
1 perry 1 PERLSYN
2 !!!PERLSYN
3 NAME
4 DESCRIPTION
5 ----
6 !!NAME
7
8
9 perlsyn - Perl syntax
10 !!DESCRIPTION
11
12
13 A Perl script consists of a sequence of declarations and
14 statements. The sequence of statements is executed just
15 once, unlike in __sed__ and __awk__ scripts, where the
16 sequence of statements is executed for each input line.
17 While this means that you must explicitly loop over the
18 lines of your input file (or files), it also means you have
19 much more control over which files and which lines you look
20 at. (Actually, I'm lying--it is possible to do an implicit
21 loop with either the __-n__ or __-p__ switch. It's
22 just not the mandatory default like it is in __sed__ and
23 __awk__.)
24
25
26 Perl is, for the most part, a free-form language. (The only
27 exception to this is format declarations, for obvious
28 reasons.) Text from a character until
29 the end of the line is a comment, and is ignored. If you
30 attempt to use /* */ C-style comments, it will be
31 interpreted either as division or pattern matching,
32 depending on the context, and C ++
33 // comments just look like a null regular
34 expression, so don't do that.
35
36
37 __Declarations__
38
39
40 The only things you need to declare in Perl are report
41 formats and subroutines--and even undefined subroutines can
42 be handled through AUTOLOAD . A variable
43 holds the undefined value (undef) until it has been
44 assigned a defined value, which is anything other than
45 undef. When used as a number, undef is
46 treated as 0; when used as a string, it is treated
47 the empty string, ; and when used as a
48 reference that isn't being assigned to, it is treated as an
49 error. If you enable warnings, you'll be notified of an
50 uninitialized value whenever you treat undef as a
51 string or a number. Well, usually. Boolean (``don't-care'')
52 contexts and operators such as ++, --,
53 +=, -=, and .= are always exempt
54 from such warnings.
55
56
57 A declaration can be put anywhere a statement can, but has
58 no effect on the execution of the primary sequence of
59 statements--declarations all take effect at compile time.
60 Typically all the declarations are put at the beginning or
61 the end of the script. However, if you're using
62 lexically-scoped private variables created with
63 my(), you'll have to make sure your format or
64 subroutine definition is within the same block scope as the
65 my if you expect to be able to access those private
66 variables.
67
68
69 Declaring a subroutine allows a subroutine name to be used
70 as if it were a list operator from that point forward in the
71 program. You can declare a subroutine without defining it by
72 saying sub name, thus:
73
74
75 sub myname;
76 $me = myname $0 or die
77 Note that ''myname()'' functions as a list operator, not as a unary operator; so be careful to use or instead of in this case. However, if you were to declare the subroutine as sub myname ($), then myname would function as a unary operator, so either or or would work.
78
79
80 Subroutines declarations can also be loaded up with the
81 require statement or both loaded and imported into
82 your namespace with a use statement. See perlmod
83 for details on this.
84
85
86 A statement sequence may contain declarations of
87 lexically-scoped variables, but apart from declaring a
88 variable name, the declaration acts like an ordinary
89 statement, and is elaborated within the sequence of
90 statements as if it were an ordinary statement. That means
91 it actually has both compile-time and run-time
92 effects.
93
94
95 __Simple statements__
96
97
98 The only kind of simple statement is an expression evaluated
99 for its side effects. Every simple statement must be
100 terminated with a semicolon, unless it is the final
101 statement in a block, in which case the semicolon is
102 optional. (A semicolon is still encouraged there if the
103 block takes up more than one line, because you may
104 eventually add another line.) Note that there are some
105 operators like eval {} and do {} that look
106 like compound statements, but aren't (they're just TERMs in
107 an expression), and thus need an explicit termination if
108 used as the last item in a statement.
109
110
111 Any simple statement may optionally be followed by a
112 ''SINGLE'' modifier, just before the
113 terminating semicolon (or block ending). The possible
114 modifiers are:
115
116
117 if EXPR
118 unless EXPR
119 while EXPR
120 until EXPR
121 foreach EXPR
122 The if and unless modifiers have the expected semantics, presuming you're a speaker of English. The foreach modifier is an iterator: For each value in EXPR , it aliases $_ to the value and executes the statement. The while and until modifiers have the usual while loopdo-BLOCK (or to the deprecated do-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated. This is so that you can write loops like:
123
124
125 do {
126 $line =
127 See ``do'' in perlfunc. Note also that the loop control statements described later will ''NOT'' work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for next) or around it (for last) to do that sort of thing. For next, just double the braces:
128
129
130 do {{
131 next if $x == $y;
132 # do something here
133 }} until $x++
134 For last, you have to be more elaborate:
135
136
137 LOOP: {
138 do {
139 last if $x = $y**2;
140 # do something here
141 } while $x++
142
143
144 __Compound statements__
145
146
147 In Perl, a sequence of statements that defines a scope is
148 called a block. Sometimes a block is delimited by the file
149 containing it (in the case of a required file, or the
150 program as a whole), and sometimes a block is delimited by
151 the extent of a string (in the case of an
152 eval).
153
154
155 But generally, a block is delimited by curly brackets, also
156 known as braces. We will call this syntactic construct a
157 BLOCK .
158
159
160 The following compound statements may be used to control
161 flow:
162
163
164 if (EXPR) BLOCK
165 if (EXPR) BLOCK else BLOCK
166 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
167 LABEL while (EXPR) BLOCK
168 LABEL while (EXPR) BLOCK continue BLOCK
169 LABEL for (EXPR; EXPR; EXPR) BLOCK
170 LABEL foreach VAR (LIST) BLOCK
171 LABEL foreach VAR (LIST) BLOCK continue BLOCK
172 LABEL BLOCK continue BLOCK
173 Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not statements. This means that the curly brackets are ''required''--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:
174
175
176 if (!open(FOO)) { die
177 The if statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which if an else goes with. If you use unless in place of if, the sense of the test is reversed.
178
179
180 The while statement executes the block as long as
181 the expression is true (does not evaluate to the null string
182 or 0 or
183 ). The LABEL is
184 optional, and if present, consists of an identifier followed
185 by a colon. The LABEL identifies the loop for
186 the loop control statements next, last,
187 and redo. If the LABEL is omitted,
188 the loop control statement refers to the innermost enclosing
189 loop. This may include dynamically looking back your
190 call-stack at run time to find the LABEL .
191 Such desperate behavior triggers a warning if you use the
192 use warnings pragma or the __-w__ flag. Unlike a
193 foreach statement, a while statement never
194 implicitly localises any variables.
195
196
197 If there is a continue BLOCK , it is
198 always executed just before the conditional is about to be
199 evaluated again, just like the third part of a for
200 loop in C. Thus it can be used to increment a loop variable,
201 even when the loop has been continued via the next
202 statement (which is similar to the C continue
203 statement).
204
205
206 __Loop Control__
207
208
209 The next command is like the continue
210 statement in C; it starts the next iteration of the
211 loop:
212
213
214 LINE: while (
215 The last command is like the break statement in C (as used in loops); it immediately exits the loop in question. The continue block, if any, is not executed:
216
217
218 LINE: while (
219 The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is ''not'' executed. This command is normally used by programs that want to lie to themselves about what was just input.
220
221
222 For example, when processing a file like
223 ''/etc/termcap''. If your input lines might end in
224 backslashes to indicate continuation, you want to skip ahead
225 and get the next record.
226
227
228 while (
229 which is Perl short-hand for the more explicitly written version:
230
231
232 LINE: while (defined($line =
233 Note that if there were a continue block on the above code, it would get executed even on discarded lines. This is often used to reset line counters or ?pat? one-time matches.
234
235
236 # inspired by :1,$g/fred/s//WILMA/
237 while (
238 If the word while is replaced by the word until, the sense of the test is reversed, but the conditional is still tested before the first iteration.
239
240
241 The loop control statements don't work in an if or
242 unless, since they aren't loops. You can double the
243 braces to make them such, though.
244
245
246 if (/pattern/) {{
247 next if /fred/;
248 next if /barney/;
249 # so something here
250 }}
251 The form while/if BLOCK BLOCK, available in Perl 4, is no longer available. Replace any occurrence of if BLOCK by if (do BLOCK).
252
253
254 __For Loops__
255
256
257 Perl's C-style for loop works like the
258 corresponding while loop; that means that
259 this:
260
261
262 for ($i = 1; $i
263 is the same as this:
264
265
266 $i = 1;
267 while ($i
268 There is one minor difference: if variables are declared with my in the initialization section of the for, the lexical scope of those variables is exactly the for loop (the body of the loop and the control sections).
269
270
271 Besides the normal array index looping, for can
272 lend itself to many other interesting applications. Here's
273 one that avoids the problem you get into if you explicitly
274 test for end-of-file on an interactive file descriptor
275 causing your program to appear to hang.
276
277
278 $on_a_tty = -t STDIN
279
280
281 __Foreach Loops__
282
283
284 The foreach loop iterates over a normal list value
285 and sets the variable VAR to be each element
286 of the list in turn. If the variable is preceded with the
287 keyword my, then it is lexically scoped, and is
288 therefore visible only within the loop. Otherwise, the
289 variable is implicitly local to the loop and regains its
290 former value upon exiting the loop. If the variable was
291 previously declared with my, it uses that variable
292 instead of the global one, but it's still localized to the
293 loop.
294
295
296 The foreach keyword is actually a synonym for the
297 for keyword, so you can use foreach for
298 readability or for for brevity. (Or because the
299 Bourne shell is more familiar to you than ''csh'', so
300 writing for comes more naturally.) If
301 VAR is omitted, $_ is set to each
302 value.
303
304
305 If any element of LIST is an lvalue, you can
306 modify it by modifying VAR inside the loop.
307 Conversely, if any element of LIST is
308 NOT an lvalue, any attempt to modify that
309 element will fail. In other words, the foreach loop
310 index variable is an implicit alias for each item in the
311 list that you're looping over.
312
313
314 If any part of LIST is an array,
315 foreach will get very confused if you add or remove
316 elements within the loop body, for example with
317 splice. So don't do that.
318
319
320 foreach probably won't do what you expect if
321 VAR is a tied or other special variable.
322 Don't do that either.
323
324
325 Examples:
326
327
328 for (@ary) { s/foo/bar/ }
329 for my $elem (@elements) {
330 $elem *= 2;
331 }
332 for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
333 print $count,
334 for (1..15) { print
335 foreach $item (split(/:[[\n:]*/, $ENV{TERMCAP})) {
336 print
337 Here's how a C programmer might code up a particular algorithm in Perl:
338
339
340 for (my $i = 0; $i
341 Whereas here's how a Perl programmer more comfortable with the idiom might do it:
342
343
344 OUTER: for my $wid (@ary1) {
345 INNER: for my $jet (@ary2) {
346 next OUTER if $wid
347 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 next explicitly iterates the other loop rather than merely terminating the inner one. And it's faster because Perl executes a foreach statement more rapidly than it would the equivalent for loop.
348
349
350 __Basic BLOCKs and Switch Statements__
351
352
353 A BLOCK by itself (labeled or not) is
354 semantically equivalent to a loop that executes once. Thus
355 you can use any of the loop control statements in it to
356 leave or restart the block. (Note that this is
357 ''NOT'' true in eval{},
358 sub{}, or contrary to popular belief do{}
359 blocks, which do ''NOT'' count as loops.)
360 The continue block is optional.
361
362
363 The BLOCK construct is particularly nice for
364 doing case structures.
365
366
367 SWITCH: {
368 if (/^abc/) { $abc = 1; last SWITCH; }
369 if (/^def/) { $def = 1; last SWITCH; }
370 if (/^xyz/) { $xyz = 1; last SWITCH; }
371 $nothing = 1;
372 }
373 There is no official switch statement in Perl, because there are already several ways to write the equivalent. In addition to the above, you could write
374
375
376 SWITCH: {
377 $abc = 1, last SWITCH if /^abc/;
378 $def = 1, last SWITCH if /^def/;
379 $xyz = 1, last SWITCH if /^xyz/;
380 $nothing = 1;
381 }
382 (That's actually not as strange as it looks once you realize that you can use loop control ``operators'' within an expression, That's just the normal C comma operator.)
383
384
385 or
386
387
388 SWITCH: {
389 /^abc/
390 or formatted so it stands out more as a ``proper'' switch statement:
391
392
393 SWITCH: {
394 /^abc/
395 /^def/
396 /^xyz/
397 or
398
399
400 SWITCH: {
401 /^abc/ and $abc = 1, last SWITCH;
402 /^def/ and $def = 1, last SWITCH;
403 /^xyz/ and $xyz = 1, last SWITCH;
404 $nothing = 1;
405 }
406 or even, horrors,
407
408
409 if (/^abc/)
410 { $abc = 1 }
411 elsif (/^def/)
412 { $def = 1 }
413 elsif (/^xyz/)
414 { $xyz = 1 }
415 else
416 { $nothing = 1 }
417 A common idiom for a switch statement is to use foreach's aliasing to make a temporary assignment to $_ for convenient matching:
418
419
420 SWITCH: for ($where) {
421 /In Card Names/
422 Another interesting approach to a switch statement is arrange for a do block to return the proper value:
423
424
425 $amode = do {
426 if ($flag
427 Or
428
429
430 print do {
431 ($flags
432 Or if you are certainly that all the clauses are true, you can use something like this, which ``switches'' on the value of the HTTP_USER_AGENT environment variable.
433
434
435 #!/usr/bin/perl
436 # pick out jargon file page based on browser
437 $dir = 'http://www.wins.uva.nl/~mes/jargon';
438 for ($ENV{HTTP_USER_AGENT}) {
439 $page = /Mac/
440 That kind of switch statement only works when you know the clauses will be true. If you don't, the previous ?: example should be used.
441
442
443 You might also consider writing a hash of subroutine
444 references instead of synthesizing a switch
445 statement.
446
447
448 __Goto__
449
450
451 Although not for the faint of heart, Perl does support a
452 goto statement. There are three forms:
453 goto-LABEL, goto-EXPR, and
454 goto-LABEL is
455 not actually a valid target for a goto; it's just
456 the name of the loop.
457
458
459 The goto-LABEL form finds the statement labeled
460 with LABEL and resumes execution there. It
461 may not be used to go into any construct that requires
462 initialization, such as a subroutine or a foreach
463 loop. It also can't be used to go into a construct that is
464 optimized away. It can be used to go almost anywhere else
465 within the dynamic scope, including out of subroutines, but
466 it's usually better to use some other construct such as
467 last or die. The author of Perl has never
468 felt the need to use this form of goto (in Perl,
469 that is--C is another matter).
470
471
472 The goto-EXPR form expects a label name, whose
473 scope will be resolved dynamically. This allows for computed
474 gotos per FORTRAN , but isn't
475 necessarily recommended if you're optimizing for
476 maintainability:
477
478
479 goto((
480 The goto-AUTOLOAD() 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 @_ in the current subroutine are propagated to the other subroutine.) After the goto, not even caller() will be able to tell that this routine was called first.
481
482
483 In almost all cases like this, it's usually a far, far
484 better idea to use the structured control flow mechanisms of
485 next, last, or redo instead of
486 resorting to a goto. For certain applications, the
487 catch and throw pair of eval{} and ''die()'' for
488 exception processing can also be a prudent
489 approach.
490
491
492 __PODs: Embedded Documentation__
493
494
495 Perl has a mechanism for intermixing documentation with
496 source code. While it's expecting the beginning of a new
497 statement, if the compiler encounters a line that begins
498 with an equal sign and a word, like this
499
500
501 =head1 Here There Be Pods!
502 Then that text and all remaining text up through and including a line beginning with =cut will be ignored. The format of the intervening text is described in perlpod.
503
504
505 This allows you to intermix your source code and your
506 documentation text freely, as in
507
508
509 =item snazzle($)
510 The snazzle() function will behave in the most spectacular
511 form that you can possibly imagine, not even excepting
512 cybernetic pyrotechnics.
513 =cut back to the compiler, nuff of this pod stuff!
514 sub snazzle($) {
515 my $thingie = shift;
516 .........
517 }
518 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.
519
520
521 $a=3;
522 =secret stuff
523 warn
524 You probably shouldn't rely upon the warn() being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.
525
526
527 One may also use pod directives to quickly comment out a
528 section of code.
529
530
531 __Plain Old Comments (Not!)__
532
533
534 Much like the C preprocessor, Perl can process line
535 directives. Using this, one can control Perl's idea of
536 filenames and line numbers in error or warning messages
537 (especially for strings that are processed with
538 eval()). The syntax for this mechanism is the same
539 as for most C preprocessors: it matches the regular
540 expression
541 /^#s*lines+(d+)s*(?:s
542 with $1 being the line number for the next line,
543 and $2 being the optional filename (specified
544 within quotes).
545
546
547 There is a fairly obvious gotcha included with the line
548 directive: Debuggers and profilers will only show the last
549 source line to appear at a particular line number in a given
550 file. Care should be taken not to cause line number
551 collisions in code you'd like to debug later.
552
553
554 Here are some examples that you should be able to type into
555 your command shell:
556
557
558 % perl
559 # line 200
560 % perl
561 # line 200
562 % perl
563 eval qq[[n#line 200
564 % perl
565 # line 345
566 ----
This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.