| EIW Fall 2003 Lecture Notes |
|   EIW Home  |   Course Syllabus |
if
unless
while
until
for
foreach
Control Structures provide a means of controlling the flow of a program. So far we've looked only at basic expressions, now we look at how to tie these expressions together in to a program that can iterate (loop) or make decisions (conditionals) based on the state of variables.
Perl contains the typical assortment of control structures including
if-then-else conditionals, while and
for loops. Perl also contains some new control structures
you may not have seen before (new to a C/C++ programmer).
if statementThe perl if statement looks much like a C if
statement. Here is the general structure:
if (expression) {
stmt1;
}
The value of expression determines whether or not
the perl statement stmt1 is executed. If the value of
expression is considered "TRUE" by perl, then
stmt1 is executed, otherwise stmt1 is skipped.
In the C language any non-zero value is considered to be TRUE and the value 0 is considered FALSE. In perl things are a bit more complex, this is necessary since we often deal with strings (not just numbers). In perl, the following determine the TRUTH of an expression:
*: There is an exception to this rule - the string "0" is FALSE
Formally, perl first converts a conditional value to a string and then if the result is either the empty string or the string "0" the expression is FALSE, otherwise it is TRUE. Note that the string "00" is considered TRUE!
The special perl value undef is considered false (formally this is because when converted to a string it has the value "").
In perl you can create a block of statements by enclosing a
sequence of statements inside curly braces { }. In C/C++
a single statment inside a control strucuture (like an IF) does not
require curly braces - in perl the curly braces are always required.
If ExamplesWe can now look at some example if statements:
|
Perl allows a sequence of statements inside the curly braces, this
sequence can include multiple if statements (any kind of
statement). Perl also supports an else continuation of
the if. A more complex example:
|
A common pattern is a sequence of if-else statements. In perl you can
combine an else with a following if with an
elsif as in this example:
|
Ever want to leave off the if part and just keep the else part of an if-else? Perl has just what you need - it's called unless. The statments inside an unless are not executed if the
conditional expression is TRUE:
|
A perl while is used to create iteration (loops). The
general form looks like this:
while (expression) {
stmt1;
... # could be more statments here
}
This is like an if except that stmt1 (and
any others inside the braces) is executed over and over as long as
expression is TRUE.
|