1N/A=head1 NAME
1N/A
1N/Aperlsyn - Perl syntax
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AA Perl program consists of a sequence of declarations and statements
1N/Awhich run from the top to the bottom. Loops, subroutines and other
1N/Acontrol structures allow you to jump around within the code.
1N/A
1N/APerl is a B<free-form> language, you can format and indent it however
1N/Ayou like. Whitespace mostly serves to separate tokens, unlike
1N/Alanguages like Python where it is an important part of the syntax.
1N/A
1N/AMany of Perl's syntactic elements are B<optional>. Rather than
1N/Arequiring you to put parentheses around every function call and
1N/Adeclare every variable, you can often leave such explicit elements off
1N/Aand Perl will figure out what you meant. This is known as B<Do What I
1N/AMean>, abbreviated B<DWIM>. It allows programmers to be B<lazy> and to
1N/Acode in a style with which they are comfortable.
1N/A
1N/APerl B<borrows syntax> and concepts from many languages: awk, sed, C,
1N/ABourne Shell, Smalltalk, Lisp and even English. Other
1N/Alanguages have borrowed syntax from Perl, particularly its regular
1N/Aexpression extensions. So if you have programmed in another language
1N/Ayou will see familiar pieces in Perl. They often work the same, but
1N/Asee L<perltrap> for information about how they differ.
1N/A
1N/A=head2 Declarations
1N/A
1N/AThe only things you need to declare in Perl are report formats and
1N/Asubroutines (and sometimes not even subroutines). A variable holds
1N/Athe undefined value (C<undef>) until it has been assigned a defined
1N/Avalue, which is anything other than C<undef>. When used as a number,
1N/AC<undef> is treated as C<0>; when used as a string, it is treated as
1N/Athe empty string, C<"">; and when used as a reference that isn't being
1N/Aassigned to, it is treated as an error. If you enable warnings,
1N/Ayou'll be notified of an uninitialized value whenever you treat
1N/AC<undef> as a string or a number. Well, usually. Boolean contexts,
1N/Asuch as:
1N/A
1N/A my $a;
1N/A if ($a) {}
1N/A
1N/Aare exempt from warnings (because they care about truth rather than
1N/Adefinedness). Operators such as C<++>, C<-->, C<+=>,
1N/AC<-=>, and C<.=>, that operate on undefined left values such as:
1N/A
1N/A my $a;
1N/A $a++;
1N/A
1N/Aare also always exempt from such warnings.
1N/A
1N/AA declaration can be put anywhere a statement can, but has no effect on
1N/Athe execution of the primary sequence of statements--declarations all
1N/Atake effect at compile time. Typically all the declarations are put at
1N/Athe beginning or the end of the script. However, if you're using
1N/Alexically-scoped private variables created with C<my()>, you'll
1N/Ahave to make sure
1N/Ayour format or subroutine definition is within the same block scope
1N/Aas the my if you expect to be able to access those private variables.
1N/A
1N/ADeclaring a subroutine allows a subroutine name to be used as if it were a
1N/Alist operator from that point forward in the program. You can declare a
1N/Asubroutine without defining it by saying C<sub name>, thus:
1N/A
1N/A sub myname;
1N/A $me = myname $0 or die "can't get myname";
1N/A
1N/ANote that myname() functions as a list operator, not as a unary operator;
1N/Aso be careful to use C<or> instead of C<||> in this case. However, if
1N/Ayou were to declare the subroutine as C<sub myname ($)>, then
1N/AC<myname> would function as a unary operator, so either C<or> or
1N/AC<||> would work.
1N/A
1N/ASubroutines declarations can also be loaded up with the C<require> statement
1N/Aor both loaded and imported into your namespace with a C<use> statement.
1N/ASee L<perlmod> for details on this.
1N/A
1N/AA statement sequence may contain declarations of lexically-scoped
1N/Avariables, but apart from declaring a variable name, the declaration acts
1N/Alike an ordinary statement, and is elaborated within the sequence of
1N/Astatements as if it were an ordinary statement. That means it actually
1N/Ahas both compile-time and run-time effects.
1N/A
1N/A=head2 Comments
1N/A
1N/AText from a C<"#"> character until the end of the line is a comment,
1N/Aand is ignored. Exceptions include C<"#"> inside a string or regular
1N/Aexpression.
1N/A
1N/A=head2 Simple Statements
1N/A
1N/AThe only kind of simple statement is an expression evaluated for its
1N/Aside effects. Every simple statement must be terminated with a
1N/Asemicolon, unless it is the final statement in a block, in which case
1N/Athe semicolon is optional. (A semicolon is still encouraged if the
1N/Ablock takes up more than one line, because you may eventually add
1N/Aanother line.) Note that there are some operators like C<eval {}> and
1N/AC<do {}> that look like compound statements, but aren't (they're just
1N/ATERMs in an expression), and thus need an explicit termination if used
1N/Aas the last item in a statement.
1N/A
1N/A=head2 Truth and Falsehood
1N/A
1N/AThe number 0, the strings C<'0'> and C<''>, the empty list C<()>, and
1N/AC<undef> are all false in a boolean context. All other values are true.
1N/A
1N/A=head2 Statement Modifiers
1N/A
1N/AAny simple statement may optionally be followed by a I<SINGLE> modifier,
1N/Ajust before the terminating semicolon (or block ending). The possible
1N/Amodifiers are:
1N/A
1N/A if EXPR
1N/A unless EXPR
1N/A while EXPR
1N/A until EXPR
1N/A foreach LIST
1N/A
1N/AThe C<EXPR> following the modifier is referred to as the "condition".
1N/AIts truth or falsehood determines how the modifier will behave.
1N/A
1N/AC<if> executes the statement once I<if> and only if the condition is
1N/Atrue. C<unless> is the opposite, it executes the statement I<unless>
1N/Athe condition is true (i.e., if the condition is false).
1N/A
1N/A print "Basset hounds got long ears" if length $ear >= 10;
1N/A go_outside() and play() unless $is_raining;
1N/A
1N/AThe C<foreach> modifier is an iterator: it executes the statement once
1N/Afor each item in the LIST (with C<$_> aliased to each item in turn).
1N/A
1N/A print "Hello $_!\n" foreach qw(world Dolly nurse);
1N/A
1N/AC<while> repeats the statement I<while> the condition is true.
1N/AC<until> does the opposite, it repeats the statement I<until> the
1N/Acondition is true (or while the condition is false):
1N/A
1N/A # Both of these count from 0 to 10.
1N/A print $i++ while $i <= 10;
1N/A print $j++ until $j > 10;
1N/A
1N/AThe C<while> and C<until> modifiers have the usual "C<while> loop"
1N/Asemantics (conditional evaluated first), except when applied to a
1N/AC<do>-BLOCK (or to the deprecated C<do>-SUBROUTINE statement), in
1N/Awhich case the block executes once before the conditional is
1N/Aevaluated. This is so that you can write loops like:
1N/A
1N/A do {
1N/A $line = <STDIN>;
1N/A ...
1N/A } until $line eq ".\n";
1N/A
1N/ASee L<perlfunc/do>. Note also that the loop control statements described
1N/Alater will I<NOT> work in this construct, because modifiers don't take
1N/Aloop labels. Sorry. You can always put another block inside of it
1N/A(for C<next>) or around it (for C<last>) to do that sort of thing.
1N/AFor C<next>, just double the braces:
1N/A
1N/A do {{
1N/A next if $x == $y;
1N/A # do something here
1N/A }} until $x++ > $z;
1N/A
1N/AFor C<last>, you have to be more elaborate:
1N/A
1N/A LOOP: {
1N/A do {
1N/A last if $x = $y**2;
1N/A # do something here
1N/A } while $x++ <= $z;
1N/A }
1N/A
1N/AB<NOTE:> The behaviour of a C<my> statement modified with a statement
1N/Amodifier conditional or loop construct (e.g. C<my $x if ...>) is
1N/AB<undefined>. The value of the C<my> variable may be C<undef>, any
1N/Apreviously assigned value, or possibly anything else. Don't rely on
1N/Ait. Future versions of perl might do something different from the
1N/Aversion of perl you try it out on. Here be dragons.
1N/A
1N/A=head2 Compound Statements
1N/A
1N/AIn Perl, a sequence of statements that defines a scope is called a block.
1N/ASometimes a block is delimited by the file containing it (in the case
1N/Aof a required file, or the program as a whole), and sometimes a block
1N/Ais delimited by the extent of a string (in the case of an eval).
1N/A
1N/ABut generally, a block is delimited by curly brackets, also known as braces.
1N/AWe will call this syntactic construct a BLOCK.
1N/A
1N/AThe following compound statements may be used to control flow:
1N/A
1N/A if (EXPR) BLOCK
1N/A if (EXPR) BLOCK else BLOCK
1N/A if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
1N/A LABEL while (EXPR) BLOCK
1N/A LABEL while (EXPR) BLOCK continue BLOCK
1N/A LABEL for (EXPR; EXPR; EXPR) BLOCK
1N/A LABEL foreach VAR (LIST) BLOCK
1N/A LABEL foreach VAR (LIST) BLOCK continue BLOCK
1N/A LABEL BLOCK continue BLOCK
1N/A
1N/ANote that, unlike C and Pascal, these are defined in terms of BLOCKs,
1N/Anot statements. This means that the curly brackets are I<required>--no
1N/Adangling statements allowed. If you want to write conditionals without
1N/Acurly brackets there are several other ways to do it. The following
1N/Aall do the same thing:
1N/A
1N/A if (!open(FOO)) { die "Can't open $FOO: $!"; }
1N/A die "Can't open $FOO: $!" unless open(FOO);
1N/A open(FOO) or die "Can't open $FOO: $!"; # FOO or bust!
1N/A open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
1N/A # a bit exotic, that last one
1N/A
1N/AThe C<if> statement is straightforward. Because BLOCKs are always
1N/Abounded by curly brackets, there is never any ambiguity about which
1N/AC<if> an C<else> goes with. If you use C<unless> in place of C<if>,
1N/Athe sense of the test is reversed.
1N/A
1N/AThe C<while> statement executes the block as long as the expression is
1N/Atrue (does not evaluate to the null string C<""> or C<0> or C<"0">).
1N/AThe LABEL is optional, and if present, consists of an identifier followed
1N/Aby a colon. The LABEL identifies the loop for the loop control
1N/Astatements C<next>, C<last>, and C<redo>.
1N/AIf the LABEL is omitted, the loop control statement
1N/Arefers to the innermost enclosing loop. This may include dynamically
1N/Alooking back your call-stack at run time to find the LABEL. Such
1N/Adesperate behavior triggers a warning if you use the C<use warnings>
1N/Apragma or the B<-w> flag.
1N/A
1N/AIf there is a C<continue> BLOCK, it is always executed just before the
1N/Aconditional is about to be evaluated again. Thus it can be used to
1N/Aincrement a loop variable, even when the loop has been continued via
1N/Athe C<next> statement.
1N/A
1N/A=head2 Loop Control
1N/A
1N/AThe C<next> command starts the next iteration of the loop:
1N/A
1N/A LINE: while (<STDIN>) {
1N/A next LINE if /^#/; # discard comments
1N/A ...
1N/A }
1N/A
1N/AThe C<last> command immediately exits the loop in question. The
1N/AC<continue> block, if any, is not executed:
1N/A
1N/A LINE: while (<STDIN>) {
1N/A last LINE if /^$/; # exit when done with header
1N/A ...
1N/A }
1N/A
1N/AThe C<redo> command restarts the loop block without evaluating the
1N/Aconditional again. The C<continue> block, if any, is I<not> executed.
1N/AThis command is normally used by programs that want to lie to themselves
1N/Aabout what was just input.
1N/A
1N/AFor example, when processing a file like F</etc/termcap>.
1N/AIf your input lines might end in backslashes to indicate continuation, you
1N/Awant to skip ahead and get the next record.
1N/A
1N/A while (<>) {
1N/A chomp;
1N/A if (s/\\$//) {
1N/A $_ .= <>;
1N/A redo unless eof();
1N/A }
1N/A # now process $_
1N/A }
1N/A
1N/Awhich is Perl short-hand for the more explicitly written version:
1N/A
1N/A LINE: while (defined($line = <ARGV>)) {
1N/A chomp($line);
1N/A if ($line =~ s/\\$//) {
1N/A $line .= <ARGV>;
1N/A redo LINE unless eof(); # not eof(ARGV)!
1N/A }
1N/A # now process $line
1N/A }
1N/A
1N/ANote that if there were a C<continue> block on the above code, it would
1N/Aget executed only on lines discarded by the regex (since redo skips the
1N/Acontinue block). A continue block is often used to reset line counters
1N/Aor C<?pat?> one-time matches:
1N/A
1N/A # inspired by :1,$g/fred/s//WILMA/
1N/A while (<>) {
1N/A ?(fred)? && s//WILMA $1 WILMA/;
1N/A ?(barney)? && s//BETTY $1 BETTY/;
1N/A ?(homer)? && s//MARGE $1 MARGE/;
1N/A } continue {
1N/A print "$ARGV $.: $_";
1N/A close ARGV if eof(); # reset $.
1N/A reset if eof(); # reset ?pat?
1N/A }
1N/A
1N/AIf the word C<while> is replaced by the word C<until>, the sense of the
1N/Atest is reversed, but the conditional is still tested before the first
1N/Aiteration.
1N/A
1N/AThe loop control statements don't work in an C<if> or C<unless>, since
1N/Athey aren't loops. You can double the braces to make them such, though.
1N/A
1N/A if (/pattern/) {{
1N/A last if /fred/;
1N/A next if /barney/; # same effect as "last", but doesn't document as well
1N/A # do something here
1N/A }}
1N/A
1N/AThis is caused by the fact that a block by itself acts as a loop that
1N/Aexecutes once, see L<"Basic BLOCKs and Switch Statements">.
1N/A
1N/AThe form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
1N/Aavailable. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
1N/A
1N/A=head2 For Loops
1N/A
1N/APerl's C-style C<for> loop works like the corresponding C<while> loop;
1N/Athat means that this:
1N/A
1N/A for ($i = 1; $i < 10; $i++) {
1N/A ...
1N/A }
1N/A
1N/Ais the same as this:
1N/A
1N/A $i = 1;
1N/A while ($i < 10) {
1N/A ...
1N/A } continue {
1N/A $i++;
1N/A }
1N/A
1N/AThere is one minor difference: if variables are declared with C<my>
1N/Ain the initialization section of the C<for>, the lexical scope of
1N/Athose variables is exactly the C<for> loop (the body of the loop
1N/Aand the control sections).
1N/A
1N/ABesides the normal array index looping, C<for> can lend itself
1N/Ato many other interesting applications. Here's one that avoids the
1N/Aproblem you get into if you explicitly test for end-of-file on
1N/Aan interactive file descriptor causing your program to appear to
1N/Ahang.
1N/A
1N/A $on_a_tty = -t STDIN && -t STDOUT;
1N/A sub prompt { print "yes? " if $on_a_tty }
1N/A for ( prompt(); <STDIN>; prompt() ) {
1N/A # do something
1N/A }
1N/A
1N/AUsing C<readline> (or the operator form, C<< <EXPR> >>) as the
1N/Aconditional of a C<for> loop is shorthand for the following. This
1N/Abehaviour is the same as a C<while> loop conditional.
1N/A
1N/A for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
1N/A # do something
1N/A }
1N/A
1N/A=head2 Foreach Loops
1N/A
1N/AThe C<foreach> loop iterates over a normal list value and sets the
1N/Avariable VAR to be each element of the list in turn. If the variable
1N/Ais preceded with the keyword C<my>, then it is lexically scoped, and
1N/Ais therefore visible only within the loop. Otherwise, the variable is
1N/Aimplicitly local to the loop and regains its former value upon exiting
1N/Athe loop. If the variable was previously declared with C<my>, it uses
1N/Athat variable instead of the global one, but it's still localized to
1N/Athe loop. This implicit localisation occurs I<only> in a C<foreach>
1N/Aloop.
1N/A
1N/AThe C<foreach> keyword is actually a synonym for the C<for> keyword, so
1N/Ayou can use C<foreach> for readability or C<for> for brevity. (Or because
1N/Athe Bourne shell is more familiar to you than I<csh>, so writing C<for>
1N/Acomes more naturally.) If VAR is omitted, C<$_> is set to each value.
1N/A
1N/AIf any element of LIST is an lvalue, you can modify it by modifying
1N/AVAR inside the loop. Conversely, if any element of LIST is NOT an
1N/Alvalue, any attempt to modify that element will fail. In other words,
1N/Athe C<foreach> loop index variable is an implicit alias for each item
1N/Ain the list that you're looping over.
1N/A
1N/AIf any part of LIST is an array, C<foreach> will get very confused if
1N/Ayou add or remove elements within the loop body, for example with
1N/AC<splice>. So don't do that.
1N/A
1N/AC<foreach> probably won't do what you expect if VAR is a tied or other
1N/Aspecial variable. Don't do that either.
1N/A
1N/AExamples:
1N/A
1N/A for (@ary) { s/foo/bar/ }
1N/A
1N/A for my $elem (@elements) {
1N/A $elem *= 2;
1N/A }
1N/A
1N/A for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
1N/A print $count, "\n"; sleep(1);
1N/A }
1N/A
1N/A for (1..15) { print "Merry Christmas\n"; }
1N/A
1N/A foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
1N/A print "Item: $item\n";
1N/A }
1N/A
1N/AHere's how a C programmer might code up a particular algorithm in Perl:
1N/A
1N/A for (my $i = 0; $i < @ary1; $i++) {
1N/A for (my $j = 0; $j < @ary2; $j++) {
1N/A if ($ary1[$i] > $ary2[$j]) {
1N/A last; # can't go to outer :-(
1N/A }
1N/A $ary1[$i] += $ary2[$j];
1N/A }
1N/A # this is where that last takes me
1N/A }
1N/A
1N/AWhereas here's how a Perl programmer more comfortable with the idiom might
1N/Ado it:
1N/A
1N/A OUTER: for my $wid (@ary1) {
1N/A INNER: for my $jet (@ary2) {
1N/A next OUTER if $wid > $jet;
1N/A $wid += $jet;
1N/A }
1N/A }
1N/A
1N/ASee how much easier this is? It's cleaner, safer, and faster. It's
1N/Acleaner because it's less noisy. It's safer because if code gets added
1N/Abetween the inner and outer loops later on, the new code won't be
1N/Aaccidentally executed. The C<next> explicitly iterates the other loop
1N/Arather than merely terminating the inner one. And it's faster because
1N/APerl executes a C<foreach> statement more rapidly than it would the
1N/Aequivalent C<for> loop.
1N/A
1N/A=head2 Basic BLOCKs and Switch Statements
1N/A
1N/AA BLOCK by itself (labeled or not) is semantically equivalent to a
1N/Aloop that executes once. Thus you can use any of the loop control
1N/Astatements in it to leave or restart the block. (Note that this is
1N/AI<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
1N/AC<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
1N/Ablock is optional.
1N/A
1N/AThe BLOCK construct is particularly nice for doing case
1N/Astructures.
1N/A
1N/A SWITCH: {
1N/A if (/^abc/) { $abc = 1; last SWITCH; }
1N/A if (/^def/) { $def = 1; last SWITCH; }
1N/A if (/^xyz/) { $xyz = 1; last SWITCH; }
1N/A $nothing = 1;
1N/A }
1N/A
1N/AThere is no official C<switch> statement in Perl, because there are
1N/Aalready several ways to write the equivalent.
1N/A
1N/AHowever, starting from Perl 5.8 to get switch and case one can use
1N/Athe Switch extension and say:
1N/A
1N/A use Switch;
1N/A
1N/Aafter which one has switch and case. It is not as fast as it could be
1N/Abecause it's not really part of the language (it's done using source
1N/Afilters) but it is available, and it's very flexible.
1N/A
1N/AIn addition to the above BLOCK construct, you could write
1N/A
1N/A SWITCH: {
1N/A $abc = 1, last SWITCH if /^abc/;
1N/A $def = 1, last SWITCH if /^def/;
1N/A $xyz = 1, last SWITCH if /^xyz/;
1N/A $nothing = 1;
1N/A }
1N/A
1N/A(That's actually not as strange as it looks once you realize that you can
1N/Ause loop control "operators" within an expression. That's just the binary
1N/Acomma operator in scalar context. See L<perlop/"Comma Operator">.)
1N/A
1N/Aor
1N/A
1N/A SWITCH: {
1N/A /^abc/ && do { $abc = 1; last SWITCH; };
1N/A /^def/ && do { $def = 1; last SWITCH; };
1N/A /^xyz/ && do { $xyz = 1; last SWITCH; };
1N/A $nothing = 1;
1N/A }
1N/A
1N/Aor formatted so it stands out more as a "proper" C<switch> statement:
1N/A
1N/A SWITCH: {
1N/A /^abc/ && do {
1N/A $abc = 1;
1N/A last SWITCH;
1N/A };
1N/A
1N/A /^def/ && do {
1N/A $def = 1;
1N/A last SWITCH;
1N/A };
1N/A
1N/A /^xyz/ && do {
1N/A $xyz = 1;
1N/A last SWITCH;
1N/A };
1N/A $nothing = 1;
1N/A }
1N/A
1N/Aor
1N/A
1N/A SWITCH: {
1N/A /^abc/ and $abc = 1, last SWITCH;
1N/A /^def/ and $def = 1, last SWITCH;
1N/A /^xyz/ and $xyz = 1, last SWITCH;
1N/A $nothing = 1;
1N/A }
1N/A
1N/Aor even, horrors,
1N/A
1N/A if (/^abc/)
1N/A { $abc = 1 }
1N/A elsif (/^def/)
1N/A { $def = 1 }
1N/A elsif (/^xyz/)
1N/A { $xyz = 1 }
1N/A else
1N/A { $nothing = 1 }
1N/A
1N/AA common idiom for a C<switch> statement is to use C<foreach>'s aliasing to make
1N/Aa temporary assignment to C<$_> for convenient matching:
1N/A
1N/A SWITCH: for ($where) {
1N/A /In Card Names/ && do { push @flags, '-e'; last; };
1N/A /Anywhere/ && do { push @flags, '-h'; last; };
1N/A /In Rulings/ && do { last; };
1N/A die "unknown value for form variable where: `$where'";
1N/A }
1N/A
1N/AAnother interesting approach to a switch statement is arrange
1N/Afor a C<do> block to return the proper value:
1N/A
1N/A $amode = do {
1N/A if ($flag & O_RDONLY) { "r" } # XXX: isn't this 0?
1N/A elsif ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
1N/A elsif ($flag & O_RDWR) {
1N/A if ($flag & O_CREAT) { "w+" }
1N/A else { ($flag & O_APPEND) ? "a+" : "r+" }
1N/A }
1N/A };
1N/A
1N/AOr
1N/A
1N/A print do {
1N/A ($flags & O_WRONLY) ? "write-only" :
1N/A ($flags & O_RDWR) ? "read-write" :
1N/A "read-only";
1N/A };
1N/A
1N/AOr if you are certain that all the C<&&> clauses are true, you can use
1N/Asomething like this, which "switches" on the value of the
1N/AC<HTTP_USER_AGENT> environment variable.
1N/A
1N/A #!/usr/bin/perl
1N/A # pick out jargon file page based on browser
1N/A $dir = 'http://www.wins.uva.nl/~mes/jargon';
1N/A for ($ENV{HTTP_USER_AGENT}) {
1N/A $page = /Mac/ && 'm/Macintrash.html'
1N/A || /Win(dows )?NT/ && 'e/evilandrude.html'
1N/A || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html'
1N/A || /Linux/ && 'l/Linux.html'
1N/A || /HP-UX/ && 'h/HP-SUX.html'
1N/A || /SunOS/ && 's/ScumOS.html'
1N/A || 'a/AppendixB.html';
1N/A }
1N/A print "Location: $dir/$page\015\012\015\012";
1N/A
1N/AThat kind of switch statement only works when you know the C<&&> clauses
1N/Awill be true. If you don't, the previous C<?:> example should be used.
1N/A
1N/AYou might also consider writing a hash of subroutine references
1N/Ainstead of synthesizing a C<switch> statement.
1N/A
1N/A=head2 Goto
1N/A
1N/AAlthough not for the faint of heart, Perl does support a C<goto>
1N/Astatement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
1N/AC<goto>-&NAME. A loop's LABEL is not actually a valid target for
1N/Aa C<goto>; it's just the name of the loop.
1N/A
1N/AThe C<goto>-LABEL form finds the statement labeled with LABEL and resumes
1N/Aexecution there. It may not be used to go into any construct that
1N/Arequires initialization, such as a subroutine or a C<foreach> loop. It
1N/Aalso can't be used to go into a construct that is optimized away. It
1N/Acan be used to go almost anywhere else within the dynamic scope,
1N/Aincluding out of subroutines, but it's usually better to use some other
1N/Aconstruct such as C<last> or C<die>. The author of Perl has never felt the
1N/Aneed to use this form of C<goto> (in Perl, that is--C is another matter).
1N/A
1N/AThe C<goto>-EXPR form expects a label name, whose scope will be resolved
1N/Adynamically. This allows for computed C<goto>s per FORTRAN, but isn't
1N/Anecessarily recommended if you're optimizing for maintainability:
1N/A
1N/A goto(("FOO", "BAR", "GLARCH")[$i]);
1N/A
1N/AThe C<goto>-&NAME form is highly magical, and substitutes a call to the
1N/Anamed subroutine for the currently running subroutine. This is used by
1N/AC<AUTOLOAD()> subroutines that wish to load another subroutine and then
1N/Apretend that the other subroutine had been called in the first place
1N/A(except that any modifications to C<@_> in the current subroutine are
1N/Apropagated to the other subroutine.) After the C<goto>, not even C<caller()>
1N/Awill be able to tell that this routine was called first.
1N/A
1N/AIn almost all cases like this, it's usually a far, far better idea to use the
1N/Astructured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
1N/Aresorting to a C<goto>. For certain applications, the catch and throw pair of
1N/AC<eval{}> and die() for exception processing can also be a prudent approach.
1N/A
1N/A=head2 PODs: Embedded Documentation
1N/A
1N/APerl has a mechanism for intermixing documentation with source code.
1N/AWhile it's expecting the beginning of a new statement, if the compiler
1N/Aencounters a line that begins with an equal sign and a word, like this
1N/A
1N/A =head1 Here There Be Pods!
1N/A
1N/AThen that text and all remaining text up through and including a line
1N/Abeginning with C<=cut> will be ignored. The format of the intervening
1N/Atext is described in L<perlpod>.
1N/A
1N/AThis allows you to intermix your source code
1N/Aand your documentation text freely, as in
1N/A
1N/A =item snazzle($)
1N/A
1N/A The snazzle() function will behave in the most spectacular
1N/A form that you can possibly imagine, not even excepting
1N/A cybernetic pyrotechnics.
1N/A
1N/A =cut back to the compiler, nuff of this pod stuff!
1N/A
1N/A sub snazzle($) {
1N/A my $thingie = shift;
1N/A .........
1N/A }
1N/A
1N/ANote that pod translators should look at only paragraphs beginning
1N/Awith a pod directive (it makes parsing easier), whereas the compiler
1N/Aactually knows to look for pod escapes even in the middle of a
1N/Aparagraph. This means that the following secret stuff will be
1N/Aignored by both the compiler and the translators.
1N/A
1N/A $a=3;
1N/A =secret stuff
1N/A warn "Neither POD nor CODE!?"
1N/A =cut back
1N/A print "got $a\n";
1N/A
1N/AYou probably shouldn't rely upon the C<warn()> being podded out forever.
1N/ANot all pod translators are well-behaved in this regard, and perhaps
1N/Athe compiler will become pickier.
1N/A
1N/AOne may also use pod directives to quickly comment out a section
1N/Aof code.
1N/A
1N/A=head2 Plain Old Comments (Not!)
1N/A
1N/APerl can process line directives, much like the C preprocessor. Using
1N/Athis, one can control Perl's idea of filenames and line numbers in
1N/Aerror or warning messages (especially for strings that are processed
1N/Awith C<eval()>). The syntax for this mechanism is the same as for most
1N/AC preprocessors: it matches the regular expression
1N/A
1N/A # example: '# line 42 "new_filename.plx"'
1N/A /^\# \s*
1N/A line \s+ (\d+) \s*
1N/A (?:\s("?)([^"]+)\2)? \s*
1N/A $/x
1N/A
1N/Awith C<$1> being the line number for the next line, and C<$3> being
1N/Athe optional filename (specified with or without quotes).
1N/A
1N/AThere is a fairly obvious gotcha included with the line directive:
1N/ADebuggers and profilers will only show the last source line to appear
1N/Aat a particular line number in a given file. Care should be taken not
1N/Ato cause line number collisions in code you'd like to debug later.
1N/A
1N/AHere are some examples that you should be able to type into your command
1N/Ashell:
1N/A
1N/A % perl
1N/A # line 200 "bzzzt"
1N/A # the `#' on the previous line must be the first char on line
1N/A die 'foo';
1N/A __END__
1N/A foo at bzzzt line 201.
1N/A
1N/A % perl
1N/A # line 200 "bzzzt"
1N/A eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
1N/A __END__
1N/A foo at - line 2001.
1N/A
1N/A % perl
1N/A eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
1N/A __END__
1N/A foo at foo bar line 200.
1N/A
1N/A % perl
1N/A # line 345 "goop"
1N/A eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
1N/A print $@;
1N/A __END__
1N/A foo at goop line 345.
1N/A
1N/A=cut