- A perl program is a sequence of statements, each terminated with a
semicolon. Control structures allow you to group those statements together
and control which ones get executed when. We will cover the four most useful
control structures:
if
, while
, for
,
and foreach
.
-
if
. The if
structure allows you to apply some
set of statements only if some condition is true. It has the following form:
if ( if-test ) {
list of statements
}
The if-test is a statement that is either true or false; The curly brackets
can contain any number of statements to execute (example).
-
while
. The while
-structure allows you to loop
some number of times while some statement is true. It has the following form:
while (while-test) {
list of statements
exit condition!
}
As long as the while
-test is true, the list of statements will
keep executing. It is therefore essential that you provide some
mechanism for the while
to eventually be false (example). If you don't, it will loop
forever (example).
-
for
. The numerical incrementing we did with the
while
structure is quite typical. There is thus a special
structure just for that sort of counting: for
. It does much the
same thing as we just did, except that all three parts are given at the top
of the loop: the initial assignment to the variable, what the test is, and
how the variable is incremented or decremented before each loop. Here's how
it looks:
for (assignment; test; increment/decrement) {
list of statements
}
This works just the same way, but it makes it easier to remember to do
all three things (example).