Loops #1

#0 | #1 | #2 | #3 | #4

We've used some simple loops already to give you an idea of what can be done with one, but now we will go over several more ways of implementing a loop. Did someone say There Is More Than One Way To Do It?

Loops are usually enclosed with braces ' { } ', and the code between them is called a block.

We use loops whenever we need to perform a set of steps repeatedly, or make some kind of decision with our script, or do something within a set of conditions.

Here's a list of the *positive conditional statements used in loop structures we discuss:

*Perl has positive and negative conditional statements. The negative ones are reversals of the positive ones, but it is recommended not to use them to avoid confusion.

For our purposes here we will only talk about positive conditionals. If you wish you can research them yourself.

if

The if loop may be the easiest to understand, since we all make these kinds of decisions every day.

"If I have enough money I'm going to buy a treat with my coffee."

my $money = 5;
if ($money == 5) {
    print "Coffee with a treat!\n";
}

This obviously (I hope it's obvious) prints "Coffee with a treat!". Note the condition of the loop is enclosed in parentheses ( () ) and the action to perform is enclosed in braces ( {} ). Recall that '==' is the comparison operator for numbers. A single '=' is an assignment operator.

if else

But what if we want to do something when the condition is not met - we don't have enough money for a treat?

my $money = 5;
if ($money == 5) {
    print "Coffee with a treat!\n";
} else {
    print "Sorry - no treat for you.\n";
}

That seems reasonable (and we still get a treat with coffee). But what if we want to cover some other conditions - not just YES or NO?

if, elsif, else


$money = 5;
if ($money >= 5) {
    print "Coffee with a treat!\n";
} elsif ($money < 5) {
    print "Sorry - no treat for you.\n";
} elsif ($money == 3) {
    print "But you can have 2 coffees.\n";
} elsif ($money == 1.5) {
    print "Just 1 coffee for you.\n";
} else {
    print "How much money do you really have?\n";
}

Note the funny spelling of elsif - programmers are known to be lazy. But we are still getting our treat with coffee.

The conditions are checked in the order they are written, 'falling' through to the next one if the condition is not true. Sometimes you can speed up an 'if' block by rearranging your conditional statements.

'if' as a statement modifier

If there is only 1 condition to be checked, sometimes you can use if as a statement modifier.

$money = 5;
print "Coffee with a treat!\n" if $money >= 5;

More loop structures coming up.