The if Statement

Once you can compare two values, you'll probably want your program to make decisions based upon that comparison.  Like all similar languages, Perl has an if control structure.  This construct uses a control expression (evaluated for its truth) and a block.  It may optionally have an else followed by a block as well.  In other words, it could look like this:

	if (some_expression) {

		true_statement_1;
		[	. . .
		true_statement_n;]

	} 
	[else {

		false_statement_1;
		[	. . .
    		false_statement_n;]

	}]

During execution, Perl evaluates the control expression.  If the expression is true, the first block (the true_statement statement[s] above) is executed.  If the expression is false, the second block (the false_statement statement[s] above) is executed instead.

For examples:

	if ($name gt 'fred') {

		print "'$name' comes after 'fred' in sorted order.\n";

	}

Or:

	if ($name gt 'fred') {

		print "'$name' comes after 'fred' in sorted order.\n";

	} 
	else {

		print "'$name' does not come after 'fred'.\n";
		print "Maybe it's the same string, in fact.\n";

	}

(If you're a C or Java hacker, you should note that the curly braces are required.  This eliminates the need for a "confusing dangling else" rule.)

It's a good idea to indent and space the contents of the blocks of code as we show here; that makes it easier to see what's going on.  If you're using a programmer's text editor, it'll do most of the work for you.

Next:  Boolean Values

OR

Other Control Structures





























Statement Blocks

A statement block is a sequence of statements, enclosed in matching curly braces.  It looks like this:

{
    first_statement;
    second_statement;
    third_statement;
    ...
    last_statement;
}

Perl executes each statement in sequence, from the first to the last.

Syntactically, a block of statements is accepted in place of any single statement, but the reverse is not true.

The final semicolon on the last statement is optional.  Thus, you can speak Perl with a C-accent (semicolon present) or Pascal-accent (semicolon absent).  To make it easier to add more statements later, we usually suggest omitting the semicolon only when the block is all on one line.  Contrast these two if blocks for examples of the two styles:

	if ($ready) { $hungry++ }
	if ($tired) {

		$sleepy = ($hungry + 1) * 2;

	}
Return to the page from whence you came