Mike Gossland’s Perl Tutorial Course for Windows

Chapter 1: Introduction 

What's Perl > Task Examples > Running Perl > Variables & Types >
Flow Control > Some Simple Scripts

Flow Control

While perl scripts tend to run from the beginning to the end, they have to decide on the correct actions to take along the way. Under some conditions, the script might run through a particular path, but under other conditions it might run through a completely different path. The decision-making that controls which parts of the program run is called flow control.

If-Else

The if-else combination is one of the most important control statements in any programming language. The idea is that if a condition is true, do one thing, and if it's not true, do something else. An example will show how it works:

$myname = "Mike";
if ( $myname eq "Mike" ) {
    print "Hi Mike\n";
} else {
    print "You're not Mike!\n";
}

While

A "while loop" is kind of like a repeated if statement. As long as a condition remains true, an action is repeated over and over. Once the condition is not true, the program moves on. Here's an example:

$x = 0;
while ( $x < 4 ) {
    print "X is less than 4\n";
    $x = $x + 1;
}
print "X is finally equal to 4"

By the way, it's possible to get stuck forever in a while loop. That would happen in the above example if we did not include the statement $x = $x + 1, because $x would remain at the value 0, and the while condition would remain true forever. You'd have to kill your program to stop it.

For

The for loop is one of the most useful flow control constructs. It allows you to specify how many times you want something done, or which items you'd like something done on. For example, let's say you wanted to repeat something 3 times.

for ( 1 .. 3 ) {
    print "I'm doing this 3 times!\n";
}

Another use for the for loop is working through an array:

@colors = ( "red", "green", "blue");
for $color ( @colors ) {
    print $color;
    print "\n";
}

will work through the array, assigning the values to the variable $color, and printing the three colors one after the other.

Hashes are often used in conjunction with the for loop and the special function "keys" which returns all the keys from a hash as an array:

$servings{pizza} = 30;
$servings{coke} = 40;
$servings{spumoni} = 12;

for $key ( keys(%servings) ) {
    print "We served $servings{$key} helpings of $key\n";
}

Now that you've seen a few pieces of perl, let's put them together into some sample scripts...

Next Page

Search this site or the web:

Google
just this site the whole web

Questions? Feedback?

Email me your comments!