PERLSYN
NAME DESCRIPTION
perlsyn - Perl syntax
A Perl script consists of a sequence of declarations and statements. The sequence of statements is executed just once, unlike in sed and awk scripts, where the sequence of statements is executed for each input line. While this means that you must explicitly loop over the lines of your input file (or files), it also means you have much more control over which files and which lines you look at. (Actually, I'm lying--it is possible to do an implicit loop with either the -n or -p switch. It's just not the mandatory default like it is in sed and awk.)
Perl is, for the most part, a free-form language. (The only exception to this is format declarations, for obvious reasons.) Text from a character until the end of the line is a comment, and is ignored. If you attempt to use /* */ C-style comments, it will be interpreted either as division or pattern matching, depending on the context, and C ++ // comments just look like a null regular expression, so don't do that.
Declarations
The only things you need to declare in Perl are report formats and subroutines--and even undefined subroutines can be handled through AUTOLOAD . A variable holds the undefined value (undef) until it has been assigned a defined value, which is anything other than undef. When used as a number, undef is treated as 0; when used as a string, it is treated the empty string, ; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat undef as a string or a number. Well, usually. Boolean (``don't-care'') contexts and operators such as ++, --,
from such warnings.
A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements--declarations all take effect at compile time. Typically all the declarations are put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with my(), you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables.
Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by
$me = myname $0 or die 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.
Subroutines declarations can also be loaded up with the require statement or both loaded and imported into your namespace with a use statement. See perlmod for details on this.
A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects.
Simple statements
The only kind of simple statement is an expression evaluated for its side effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. (A semicolon is still encouraged there if the block takes up more than one line, because you may eventually add another line.) Note that there are some operators like eval {} and do {} that look like compound statements, but aren't (they're just TERMs in an expression), and thus need an explicit termination if used as the last item in a statement.
Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending). The possible
unless EXPR while EXPR until EXPR foreach EXPR
$line =
next if $x == $y;
}} until $x++
do { last if $x = $y**2;
} while $x++
Compound statements
In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval).
But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK .
The following compound statements may be used to control
if (EXPR) BLOCK else BLOCK if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK LABEL while (EXPR) BLOCK LABEL while (EXPR) BLOCK continue BLOCK LABEL for (EXPR; EXPR; EXPR) BLOCK LABEL foreach VAR (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK LABEL BLOCK continue BLOCK
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.
The while statement executes the block as long as the expression is true (does not evaluate to the null string
or 0 or
). The LABEL is optional, and if present, consists of an identifier followed by a colon. The LABEL identifies the loop for the loop control statements next, last, and redo. If the LABEL is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically looking back your call-stack at run time to find the LABEL . Such desperate behavior triggers a warning if you use the use warnings pragma or the -w flag. Unlike a foreach statement, a while statement never implicitly localises any variables.
If there is a continue BLOCK , it is always executed just before the conditional is about to be evaluated again, just like the third part of a for loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the next statement (which is similar to the C continue statement).
Loop Control
The next command is like the continue statement in C; it starts the next iteration of the
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.
For example, when processing a file like /etc/termcap. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record.
while (
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.
while ( 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.
The loop control statements don't work in an if or unless, since they aren't loops. You can double the braces to make them such, though.
if (/pattern/) {{
next if /fred/; next if /barney/;
}} The form while/if BLOCK BLOCK, available in Perl 4, is no longer available. Replace any occurrence of if BLOCK by if (do BLOCK).
For Loops
Perl's C-style for loop works like the corresponding while loop; that means that
while ($i 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).
Besides the normal array index looping, for can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang.
$on_a_tty = -t STDIN
Foreach Loops
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop.
The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) If VAR is omitted, $_ is set to each value.
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.
If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.
foreach probably won't do what you expect if VAR is a tied or other special variable. Don't do that either.
$elem *= 2; }
for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
print $count,
for (1..15) { print foreach $item (split(/:?*/, $ENV{TERMCAP})) {
INNER: for my $jet (@ary2) { next OUTER if $wid 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.
Basic BLOCKs and Switch Statements
A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is NOT true in eval{}, sub{}, or contrary to popular belief do{} blocks, which do NOT count as loops.) The continue block is optional.
The BLOCK construct is particularly nice for doing case structures.
SWITCH: {
if (/^abc/) { $abc = 1; last SWITCH; } if (/^def/) { $def = 1; last SWITCH; } if (/^xyz/) { $xyz = 1; last SWITCH; } $nothing = 1; } 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
SWITCH: {
$abc = 1, last SWITCH if /^abc/; $def = 1, last SWITCH if /^def/; $xyz = 1, last SWITCH if /^xyz/; $nothing = 1; } (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.)
or
SWITCH: {
/^abc/
/^abc/
/^def/ /^xyz/
or
SWITCH: {
/^abc/ and $abc = 1, last SWITCH; /^def/ and $def = 1, last SWITCH; /^xyz/ and $xyz = 1, last SWITCH; $nothing = 1; } or even, horrors,
if (/^abc/)
{ $abc = 1 } elsif (/^def/) { $def = 1 } elsif (/^xyz/) { $xyz = 1 } else { $nothing = 1 }
/In Card Names/
if ($flag Or
print do {
($flags 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.
$dir = 'http://www.wins.uva.nl/mes/jargon'; for ($ENV{HTTP_USER_AGENT}) { $page = /Mac/ 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.
You might also consider writing a hash of subroutine references instead of synthesizing a switch statement.
Goto
Although not for the faint of heart, Perl does support a goto statement. There are three forms: goto-LABEL, goto-EXPR, and goto-LABEL is not actually a valid target for a goto; it's just the name of the loop.
The goto-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a foreach loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as last or die. The author of Perl has never felt the need to use this form of goto (in Perl, that is--C is another matter).
The goto-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed gotos per FORTRAN , but isn't necessarily recommended if you're optimizing for
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.
In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of next, last, or redo instead of resorting to a goto. For certain applications, the catch and throw pair of eval{} and die() for exception processing can also be a prudent approach.
PODs: Embedded Documentation
Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this
=head1 Here There Be Pods!
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.
This allows you to intermix your source code and your documentation text freely, as in
=item snazzle($) The snazzle() function will behave in the most spectacular
form that you can possibly imagine, not even excepting cybernetic pyrotechnics.
=cut back to the compiler, nuff of this pod stuff! sub snazzle($) {
my $thingie = shift; ......... } 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.
$a=3;
=secret stuff warn 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.
One may also use pod directives to quickly comment out a section of code.
Plain Old Comments (Not!)
Much like the C preprocessor, Perl can process line directives. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with eval()). The syntax for this mechanism is the same as for most C preprocessors: it matches the regular expression /^#s*lines+(d+)s*(?:s with $1 being the line number for the next line, and $2 being the optional filename (specified within quotes).
There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later.
Here are some examples that you should be able to type into
line 200
% perl
line 200
% perl
eval qq[[n#line 200
% perl
One page links to perlsyn(1):