Contents:
Statement Blocks
The if/unless Statement
The while/until Statement
The do {} while/until Statement
The for Statement
The foreach Statement
Exercises
A statement block is a sequence of statements, enclosed in matching curly braces. It looks like this:
{ first_statement; second_statement; third_statement; ... last_statement; }
Perl executes each statement in sequence, from the first to the last. (Later, I'll show you how to alter this execution sequence within a block, but this is good enough for now.)
Syntactically, a block of statements is accepted in place of any single statement, but the reverse is not true.
The final semicolon on the last statement is optional. Thus, you can speak Perl with a C-accent (semicolon present) or Pascal-accent (semicolon absent). To make adding more statements at a later time easier, we usually suggest omitting the semicolon only when the block is all on one line. Contrast these two if
blocks for examples of the two styles:
if ($ready) { $hungry++ } if ($tired) { $sleepy = ($hungry + 1) * 2; }