4.3 StatementsA simple statement is an expression evaluated for its side effects. Every simple statement must end in a semicolon, unless it is the final statement in a block.
A sequence of statements that defines a scope is called a
block
.
Generally, a block is delimited by braces, or
Any block can be given a label.
Labels
are identifiers that follow the variable-naming rules (i.e.,
they begin with a letter or underscore, and can contain alphanumerics and
underscores).
They are placed just before the block and are followed by a colon,
like By convention, labels are all uppercase, so as not to conflict with reserved words. Labels are used with the loop-control commandsSOMELABEL: { ... statements ... }
next
,
last
, and
redo
to alter
the flow of execution
in your programs.
4.3.1 Conditionals and Loops
The if ( expression ) { block } else { block } unless ( expression ) { block } else { block } if ( expression1 ) { block } elsif ( expression2 ) { block } ... elsif ( lastexpression ) { block } else { block } 4.3.1.1 while loops
The This loop reads each line from the file opened with the filehandle INFILE and prints them to the OUTFILE filehandle. The loop will cease when it encounters an end-of-file.while (<INFILE>) { print OUTFILE, "$_\n"; }
If the word
The 4.3.1.2 for loops
The is the same as:for ($i = 1; $i < 10; $i++) { ... } $i = 1; while ($i < 10) { ... } continue { $i++; } 4.3.1.3 foreach loops
The Like theforeach var ( list ) { ... }
while
statement, the
foreach
statement can also
take a
continue
block.
4.3.1.4 ModifiersAny simple statement may be followed by a single modifier that gives the statement a conditional or looping mechanism. This syntax provides a simpler and often more elegant method than using the corresponding compound statements. These modifiers are: For example:statement if EXPR ; statement unless EXPR ; statement while EXPR ; statement until EXPR ; The conditional is evaluated first with the$i = $num if ($num < 50); # $i will be less than 50 $j = $cnt unless ($cnt < 100); # $j will equal 100 or greater $lines++ while <FILE>; print "$_\n" until /The end/;
while
and
until
modifiers
except when applied to a
do {}
statement, in
which case the block executes once before the conditional is evaluated.
For example:
For more information ondo { $line = <STDIN>; ... } until $line eq ".\n";
do
, see
Chapter 5,
Function Reference
.
4.3.1.5 Loop control
You can put a label on a loop to give it a name. The
loop's label
identifies the loop for the loop-control commands The syntax for the loop-control commands is:LINE: while (<SCRIPT>) { print; next LINE if /^#/; # discard comments } If the label is omitted, the loop-control command refers to the innermost enclosing loop.last label next label redo label
The
The
The 4.3.1.6 goto
Perl supports a
The
The
The Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|