Using Flow Control Statements

So far, you have seen Perl statements intended to execute in a serial fashion, one after another. Perl also includes statements that enable you to control the flow of execution of the statements. You already have seen the if statement and a while loop. Perl includes a complete set of flow-control statements just like those in C, but with a few extra features.

In Perl, all conditional statements take the following form:


{ Perl code to execute if conditional is true }

Notice that you must enclose within braces ({...}) the code that follows the conditional statement. The conditional statement checks the value of an expression to determine whether to execute the code within the braces. In Perl, as in C, any nonzero value is considered true, whereas a zero value is false.

The following sections briefly describe the syntax of the major conditional statements in Perl.

Using if and unless Statements

The Perl if statement resembles the C if statement. For example, an if statement might check a count to see whether the count exceeds a threshold, as follows:

if ( $count > 25 ) { print "Too many errors!\n"; } You can add an else clause to the if statement, as follows:

print "Starting simulation...\n";

print "Sorry $user, you must be \"root\" to run this program.\n."; exit;

If you know C, you can see that Perl's syntax looks quite a bit like that in C. Conditionals with the if statement can have zero or more elsif clauses to account for more alternatives, such as the following:

print "Enter version number:"; # prompt user for version number $os_version = <STDIN>; # read from standard input chop $os_version; # get rid of the newline at the end of the line # Check version number if ($os_version >= 10 ) { print "No upgrade necessary\n";} elsif ($os_version >= 6 && $os_version < 9)

{ print "Standard upgrade\n";} elsif ($os_version > 3 && $os_version < 6) { print "Reinstall\n";} else { print "Sorry, cannot upgrade\n";}

The unless statement is unique to Perl. This statement has the same form as if, including the use of elsif and else clauses. The difference is that unless executes its statement block only if the condition is false. You can, for example, use the following:

print "You must be \"root\" to run this program.\n"; exit;

In this case, unless the string user is "root", the script exits.

Using the while Statement

Use Perl's while statement for looping, the repetition of some processing until a condition becomes false. To read a line at a time from standard input and to process that line, you might use the following:

# Code to process the line print $in;

If you read from the standard input without any argument, Perl assigns the current line of standard input to the $_variable. Thus, you can write the while loop to read lines from the standard input, as follows:


Perl's while statements are more versatile than those of C because you can use almost anything as the condition to be tested. If you use an array as the condition, for example, the while loop executes until the array has no elements left, as in the following example:

# Assume @arglist has the current set of command arguments while (@arglist) {

$arg = shift @arglist; # this extracts one argument

# Code to process the current argument print $arg;

The shift function removes the first element of an array and returns that element.

You can skip to the end of a loop with the next keyword; the last keyword exits the loop. The following while loop adds the numbers from 1 to 10, skipping 5:

if($i == 5) { next;} # Jump to the next iteration if $i is 5 if($i > 10) { last;} # When $i exceeds 10, end the loop $sum += $i; # Add the numbers

# At this point $sum should be 50. Using for and foreach Statements

Perl and C's for statements have similar syntax. Use the for statement to execute a statement any number of times, based on the value of an expression. The syntax of the for statement is as follows:

expr_1 is evaluated one time, at the beginning of the loop; the statement block is executed until expression expr_2 evaluates to zero. The third expression, expr_3, is evaluated after each execution of the statement block. You can omit any of the expressions, but you must include the semicolons. In addition, the braces around the statement block are required. Following is an example that uses a for loop to add the numbers from 1 to 10:

for($i=0, $sum=0; $i <= 10; $sum += $i, $i++) {}

In this example, the actual work of adding the numbers is done in the third expression, and the statement the for loop controls is an empty block ({}).


The foreach statement is most appropriate for processing arrays. Following is the syntax of the foreach statement:

foreach Variable (Array) { statement block }

The foreach statement assigns to Variable an element from the Array and executes the statement block. The foreach statement repeats this procedure until no array elements remain. The following foreach statement adds the numbers from 1 to 10:

Notice that I declare the array with the range operator (..). You also can use a list of comma-separated items as the array.

If you omit the Variable in a foreach statement, Perl automatically uses the $_ variable to hold the current array element. Thus, you can use the following:

Using the goto Statement

The goto statement transfers control to a statement label. Following is an example that prompts the user for a value and repeats the request, if the value is not acceptable:


print "Enter offset: "; $offset = <STDIN>; chop $offset;

unless ($offset > 0 && $offset < 512) {

print "Bad offset: $offset\n"; goto ReEnter;

Was this article helpful?

0 0
Make Money Writing

Make Money Writing

This Report Will Show You How To Make Money By Providing Writing Services To Other Internet Marketers. Learn how to make money by writing the right way. Grab your copy of this report now and learn. Why writing is a great way to earn money. How to compete with cheap writers, even if you charge a lot more money.

Get My Free Ebook

Post a comment