7 A Perl script consists of a sequence of declarations and statements.
8 The sequence of statements is executed just once, unlike in B<sed>
9 and B<awk> scripts, where the sequence of statements is executed
10 for each input line. While this means that you must explicitly
11 loop over the lines of your input file (or files), it also means
12 you have much more control over which files and which lines you look at.
13 (Actually, I'm lying--it is possible to do an implicit loop with
14 either the B<-n> or B<-p> switch. It's just not the mandatory
15 default like it is in B<sed> and B<awk>.)
17 Perl is, for the most part, a free-form language. (The only exception
18 to this is format declarations, for obvious reasons.) Text from a
19 C<"#"> character until the end of the line is a comment, and is
20 ignored. If you attempt to use C</* */> C-style comments, it will be
21 interpreted either as division or pattern matching, depending on the
22 context, and C++ C<//> comments just look like a null regular
23 expression, so don't do that.
27 The only things you need to declare in Perl are report formats
28 and subroutines--and even undefined subroutines can be handled
29 through AUTOLOAD. A variable holds the undefined value (C<undef>)
30 until it has been assigned a defined value, which is anything
31 other than C<undef>. When used as a number, C<undef> is treated
32 as C<0>; when used as a string, it is treated the empty string,
33 C<"">; and when used as a reference that isn't being assigned
34 to, it is treated as an error. If you enable warnings, you'll
35 be notified of an uninitialized value whenever you treat C<undef>
36 as a string or a number. Well, usually. Boolean contexts, such as:
41 are exempt from warnings (because they care about truth rather than
42 definedness). Operators such as C<++>, C<-->, C<+=>,
43 C<-=>, and C<.=>, that operate on undefined left values such as:
48 are also always exempt from such warnings.
50 A declaration can be put anywhere a statement can, but has no effect on
51 the execution of the primary sequence of statements--declarations all
52 take effect at compile time. Typically all the declarations are put at
53 the beginning or the end of the script. However, if you're using
54 lexically-scoped private variables created with C<my()>, you'll
56 your format or subroutine definition is within the same block scope
57 as the my if you expect to be able to access those private variables.
59 Declaring a subroutine allows a subroutine name to be used as if it were a
60 list operator from that point forward in the program. You can declare a
61 subroutine without defining it by saying C<sub name>, thus:
64 $me = myname $0 or die "can't get myname";
66 Note that myname() functions as a list operator, not as a unary operator;
67 so be careful to use C<or> instead of C<||> in this case. However, if
68 you were to declare the subroutine as C<sub myname ($)>, then
69 C<myname> would function as a unary operator, so either C<or> or
72 Subroutines declarations can also be loaded up with the C<require> statement
73 or both loaded and imported into your namespace with a C<use> statement.
74 See L<perlmod> for details on this.
76 A statement sequence may contain declarations of lexically-scoped
77 variables, but apart from declaring a variable name, the declaration acts
78 like an ordinary statement, and is elaborated within the sequence of
79 statements as if it were an ordinary statement. That means it actually
80 has both compile-time and run-time effects.
82 =head2 Simple statements
84 The only kind of simple statement is an expression evaluated for its
85 side effects. Every simple statement must be terminated with a
86 semicolon, unless it is the final statement in a block, in which case
87 the semicolon is optional. (A semicolon is still encouraged there if the
88 block takes up more than one line, because you may eventually add another line.)
89 Note that there are some operators like C<eval {}> and C<do {}> that look
90 like compound statements, but aren't (they're just TERMs in an expression),
91 and thus need an explicit termination if used as the last item in a statement.
93 Any simple statement may optionally be followed by a I<SINGLE> modifier,
94 just before the terminating semicolon (or block ending). The possible
103 The C<if> and C<unless> modifiers have the expected semantics,
104 presuming you're a speaker of English. The C<foreach> modifier is an
105 iterator: For each value in EXPR, it aliases C<$_> to the value and
106 executes the statement. The C<while> and C<until> modifiers have the
107 usual "C<while> loop" semantics (conditional evaluated first), except
108 when applied to a C<do>-BLOCK (or to the deprecated C<do>-SUBROUTINE
109 statement), in which case the block executes once before the
110 conditional is evaluated. This is so that you can write loops like:
115 } until $line eq ".\n";
117 See L<perlfunc/do>. Note also that the loop control statements described
118 later will I<NOT> work in this construct, because modifiers don't take
119 loop labels. Sorry. You can always put another block inside of it
120 (for C<next>) or around it (for C<last>) to do that sort of thing.
121 For C<next>, just double the braces:
128 For C<last>, you have to be more elaborate:
137 =head2 Compound statements
139 In Perl, a sequence of statements that defines a scope is called a block.
140 Sometimes a block is delimited by the file containing it (in the case
141 of a required file, or the program as a whole), and sometimes a block
142 is delimited by the extent of a string (in the case of an eval).
144 But generally, a block is delimited by curly brackets, also known as braces.
145 We will call this syntactic construct a BLOCK.
147 The following compound statements may be used to control flow:
150 if (EXPR) BLOCK else BLOCK
151 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
152 LABEL while (EXPR) BLOCK
153 LABEL while (EXPR) BLOCK continue BLOCK
154 LABEL for (EXPR; EXPR; EXPR) BLOCK
155 LABEL foreach VAR (LIST) BLOCK
156 LABEL foreach VAR (LIST) BLOCK continue BLOCK
157 LABEL BLOCK continue BLOCK
159 Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
160 not statements. This means that the curly brackets are I<required>--no
161 dangling statements allowed. If you want to write conditionals without
162 curly brackets there are several other ways to do it. The following
163 all do the same thing:
165 if (!open(FOO)) { die "Can't open $FOO: $!"; }
166 die "Can't open $FOO: $!" unless open(FOO);
167 open(FOO) or die "Can't open $FOO: $!"; # FOO or bust!
168 open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
169 # a bit exotic, that last one
171 The C<if> statement is straightforward. Because BLOCKs are always
172 bounded by curly brackets, there is never any ambiguity about which
173 C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
174 the sense of the test is reversed.
176 The C<while> statement executes the block as long as the expression is
177 true (does not evaluate to the null string C<""> or C<0> or C<"0">).
178 The LABEL is optional, and if present, consists of an identifier followed
179 by a colon. The LABEL identifies the loop for the loop control
180 statements C<next>, C<last>, and C<redo>.
181 If the LABEL is omitted, the loop control statement
182 refers to the innermost enclosing loop. This may include dynamically
183 looking back your call-stack at run time to find the LABEL. Such
184 desperate behavior triggers a warning if you use the C<use warnings>
185 pragma or the B<-w> flag.
186 Unlike a C<foreach> statement, a C<while> statement never implicitly
187 localises any variables.
189 If there is a C<continue> BLOCK, it is always executed just before the
190 conditional is about to be evaluated again, just like the third part of a
191 C<for> loop in C. Thus it can be used to increment a loop variable, even
192 when the loop has been continued via the C<next> statement (which is
193 similar to the C C<continue> statement).
197 The C<next> command is like the C<continue> statement in C; it starts
198 the next iteration of the loop:
200 LINE: while (<STDIN>) {
201 next LINE if /^#/; # discard comments
205 The C<last> command is like the C<break> statement in C (as used in
206 loops); it immediately exits the loop in question. The
207 C<continue> block, if any, is not executed:
209 LINE: while (<STDIN>) {
210 last LINE if /^$/; # exit when done with header
214 The C<redo> command restarts the loop block without evaluating the
215 conditional again. The C<continue> block, if any, is I<not> executed.
216 This command is normally used by programs that want to lie to themselves
217 about what was just input.
219 For example, when processing a file like F</etc/termcap>.
220 If your input lines might end in backslashes to indicate continuation, you
221 want to skip ahead and get the next record.
232 which is Perl short-hand for the more explicitly written version:
234 LINE: while (defined($line = <ARGV>)) {
236 if ($line =~ s/\\$//) {
238 redo LINE unless eof(); # not eof(ARGV)!
243 Note that if there were a C<continue> block on the above code, it would
244 get executed only on lines discarded by the regex (since redo skips the
245 continue block). A continue block is often used to reset line counters
246 or C<?pat?> one-time matches:
248 # inspired by :1,$g/fred/s//WILMA/
250 ?(fred)? && s//WILMA $1 WILMA/;
251 ?(barney)? && s//BETTY $1 BETTY/;
252 ?(homer)? && s//MARGE $1 MARGE/;
254 print "$ARGV $.: $_";
255 close ARGV if eof(); # reset $.
256 reset if eof(); # reset ?pat?
259 If the word C<while> is replaced by the word C<until>, the sense of the
260 test is reversed, but the conditional is still tested before the first
263 The loop control statements don't work in an C<if> or C<unless>, since
264 they aren't loops. You can double the braces to make them such, though.
268 next if /barney/; # same effect as "last", but doesn't document as well
272 This is caused by the fact that a block by itself acts as a loop that
273 executes once, see L<"Basic BLOCKs and Switch Statements">.
275 The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
276 available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
280 Perl's C-style C<for> loop works like the corresponding C<while> loop;
281 that means that this:
283 for ($i = 1; $i < 10; $i++) {
296 There is one minor difference: if variables are declared with C<my>
297 in the initialization section of the C<for>, the lexical scope of
298 those variables is exactly the C<for> loop (the body of the loop
299 and the control sections).
301 Besides the normal array index looping, C<for> can lend itself
302 to many other interesting applications. Here's one that avoids the
303 problem you get into if you explicitly test for end-of-file on
304 an interactive file descriptor causing your program to appear to
307 $on_a_tty = -t STDIN && -t STDOUT;
308 sub prompt { print "yes? " if $on_a_tty }
309 for ( prompt(); <STDIN>; prompt() ) {
315 The C<foreach> loop iterates over a normal list value and sets the
316 variable VAR to be each element of the list in turn. If the variable
317 is preceded with the keyword C<my>, then it is lexically scoped, and
318 is therefore visible only within the loop. Otherwise, the variable is
319 implicitly local to the loop and regains its former value upon exiting
320 the loop. If the variable was previously declared with C<my>, it uses
321 that variable instead of the global one, but it's still localized to
324 The C<foreach> keyword is actually a synonym for the C<for> keyword, so
325 you can use C<foreach> for readability or C<for> for brevity. (Or because
326 the Bourne shell is more familiar to you than I<csh>, so writing C<for>
327 comes more naturally.) If VAR is omitted, C<$_> is set to each value.
329 If any element of LIST is an lvalue, you can modify it by modifying
330 VAR inside the loop. Conversely, if any element of LIST is NOT an
331 lvalue, any attempt to modify that element will fail. In other words,
332 the C<foreach> loop index variable is an implicit alias for each item
333 in the list that you're looping over.
335 If any part of LIST is an array, C<foreach> will get very confused if
336 you add or remove elements within the loop body, for example with
337 C<splice>. So don't do that.
339 C<foreach> probably won't do what you expect if VAR is a tied or other
340 special variable. Don't do that either.
344 for (@ary) { s/foo/bar/ }
346 for my $elem (@elements) {
350 for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
351 print $count, "\n"; sleep(1);
354 for (1..15) { print "Merry Christmas\n"; }
356 foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
357 print "Item: $item\n";
360 Here's how a C programmer might code up a particular algorithm in Perl:
362 for (my $i = 0; $i < @ary1; $i++) {
363 for (my $j = 0; $j < @ary2; $j++) {
364 if ($ary1[$i] > $ary2[$j]) {
365 last; # can't go to outer :-(
367 $ary1[$i] += $ary2[$j];
369 # this is where that last takes me
372 Whereas here's how a Perl programmer more comfortable with the idiom might
375 OUTER: for my $wid (@ary1) {
376 INNER: for my $jet (@ary2) {
377 next OUTER if $wid > $jet;
382 See how much easier this is? It's cleaner, safer, and faster. It's
383 cleaner because it's less noisy. It's safer because if code gets added
384 between the inner and outer loops later on, the new code won't be
385 accidentally executed. The C<next> explicitly iterates the other loop
386 rather than merely terminating the inner one. And it's faster because
387 Perl executes a C<foreach> statement more rapidly than it would the
388 equivalent C<for> loop.
390 =head2 Basic BLOCKs and Switch Statements
392 A BLOCK by itself (labeled or not) is semantically equivalent to a
393 loop that executes once. Thus you can use any of the loop control
394 statements in it to leave or restart the block. (Note that this is
395 I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
396 C<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
399 The BLOCK construct is particularly nice for doing case
403 if (/^abc/) { $abc = 1; last SWITCH; }
404 if (/^def/) { $def = 1; last SWITCH; }
405 if (/^xyz/) { $xyz = 1; last SWITCH; }
409 There is no official C<switch> statement in Perl, because there are
410 already several ways to write the equivalent.
412 However, starting from Perl 5.8 to get switch and case one can use
413 the Switch extension and say:
417 after which one has switch and case. It is not as fast as it could be
418 because it's not really part of the language (it's done using source
419 filters) but it is available, and it's very flexible.
421 In addition to the above BLOCK construct, you could write
424 $abc = 1, last SWITCH if /^abc/;
425 $def = 1, last SWITCH if /^def/;
426 $xyz = 1, last SWITCH if /^xyz/;
430 (That's actually not as strange as it looks once you realize that you can
431 use loop control "operators" within an expression, That's just the normal
437 /^abc/ && do { $abc = 1; last SWITCH; };
438 /^def/ && do { $def = 1; last SWITCH; };
439 /^xyz/ && do { $xyz = 1; last SWITCH; };
443 or formatted so it stands out more as a "proper" C<switch> statement:
466 /^abc/ and $abc = 1, last SWITCH;
467 /^def/ and $def = 1, last SWITCH;
468 /^xyz/ and $xyz = 1, last SWITCH;
483 A common idiom for a C<switch> statement is to use C<foreach>'s aliasing to make
484 a temporary assignment to C<$_> for convenient matching:
486 SWITCH: for ($where) {
487 /In Card Names/ && do { push @flags, '-e'; last; };
488 /Anywhere/ && do { push @flags, '-h'; last; };
489 /In Rulings/ && do { last; };
490 die "unknown value for form variable where: `$where'";
493 Another interesting approach to a switch statement is arrange
494 for a C<do> block to return the proper value:
497 if ($flag & O_RDONLY) { "r" } # XXX: isn't this 0?
498 elsif ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
499 elsif ($flag & O_RDWR) {
500 if ($flag & O_CREAT) { "w+" }
501 else { ($flag & O_APPEND) ? "a+" : "r+" }
508 ($flags & O_WRONLY) ? "write-only" :
509 ($flags & O_RDWR) ? "read-write" :
513 Or if you are certain that all the C<&&> clauses are true, you can use
514 something like this, which "switches" on the value of the
515 C<HTTP_USER_AGENT> environment variable.
518 # pick out jargon file page based on browser
519 $dir = 'http://www.wins.uva.nl/~mes/jargon';
520 for ($ENV{HTTP_USER_AGENT}) {
521 $page = /Mac/ && 'm/Macintrash.html'
522 || /Win(dows )?NT/ && 'e/evilandrude.html'
523 || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html'
524 || /Linux/ && 'l/Linux.html'
525 || /HP-UX/ && 'h/HP-SUX.html'
526 || /SunOS/ && 's/ScumOS.html'
527 || 'a/AppendixB.html';
529 print "Location: $dir/$page\015\012\015\012";
531 That kind of switch statement only works when you know the C<&&> clauses
532 will be true. If you don't, the previous C<?:> example should be used.
534 You might also consider writing a hash of subroutine references
535 instead of synthesizing a C<switch> statement.
539 Although not for the faint of heart, Perl does support a C<goto>
540 statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
541 C<goto>-&NAME. A loop's LABEL is not actually a valid target for
542 a C<goto>; it's just the name of the loop.
544 The C<goto>-LABEL form finds the statement labeled with LABEL and resumes
545 execution there. It may not be used to go into any construct that
546 requires initialization, such as a subroutine or a C<foreach> loop. It
547 also can't be used to go into a construct that is optimized away. It
548 can be used to go almost anywhere else within the dynamic scope,
549 including out of subroutines, but it's usually better to use some other
550 construct such as C<last> or C<die>. The author of Perl has never felt the
551 need to use this form of C<goto> (in Perl, that is--C is another matter).
553 The C<goto>-EXPR form expects a label name, whose scope will be resolved
554 dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
555 necessarily recommended if you're optimizing for maintainability:
557 goto(("FOO", "BAR", "GLARCH")[$i]);
559 The C<goto>-&NAME form is highly magical, and substitutes a call to the
560 named subroutine for the currently running subroutine. This is used by
561 C<AUTOLOAD()> subroutines that wish to load another subroutine and then
562 pretend that the other subroutine had been called in the first place
563 (except that any modifications to C<@_> in the current subroutine are
564 propagated to the other subroutine.) After the C<goto>, not even C<caller()>
565 will be able to tell that this routine was called first.
567 In almost all cases like this, it's usually a far, far better idea to use the
568 structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
569 resorting to a C<goto>. For certain applications, the catch and throw pair of
570 C<eval{}> and die() for exception processing can also be a prudent approach.
572 =head2 PODs: Embedded Documentation
574 Perl has a mechanism for intermixing documentation with source code.
575 While it's expecting the beginning of a new statement, if the compiler
576 encounters a line that begins with an equal sign and a word, like this
578 =head1 Here There Be Pods!
580 Then that text and all remaining text up through and including a line
581 beginning with C<=cut> will be ignored. The format of the intervening
582 text is described in L<perlpod>.
584 This allows you to intermix your source code
585 and your documentation text freely, as in
589 The snazzle() function will behave in the most spectacular
590 form that you can possibly imagine, not even excepting
591 cybernetic pyrotechnics.
593 =cut back to the compiler, nuff of this pod stuff!
600 Note that pod translators should look at only paragraphs beginning
601 with a pod directive (it makes parsing easier), whereas the compiler
602 actually knows to look for pod escapes even in the middle of a
603 paragraph. This means that the following secret stuff will be
604 ignored by both the compiler and the translators.
608 warn "Neither POD nor CODE!?"
612 You probably shouldn't rely upon the C<warn()> being podded out forever.
613 Not all pod translators are well-behaved in this regard, and perhaps
614 the compiler will become pickier.
616 One may also use pod directives to quickly comment out a section
619 =head2 Plain Old Comments (Not!)
621 Much like the C preprocessor, Perl can process line directives. Using
622 this, one can control Perl's idea of filenames and line numbers in
623 error or warning messages (especially for strings that are processed
624 with C<eval()>). The syntax for this mechanism is the same as for most
625 C preprocessors: it matches the regular expression
626 C</^#\s*line\s+(\d+)\s*(?:\s"([^"]+)")?\s*$/> with C<$1> being the line
627 number for the next line, and C<$2> being the optional filename
628 (specified within quotes).
630 There is a fairly obvious gotcha included with the line directive:
631 Debuggers and profilers will only show the last source line to appear
632 at a particular line number in a given file. Care should be taken not
633 to cause line number collisions in code you'd like to debug later.
635 Here are some examples that you should be able to type into your command
640 # the `#' on the previous line must be the first char on line
643 foo at bzzzt line 201.
647 eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
652 eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
654 foo at foo bar line 200.
658 eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
661 foo at goop line 345.