New Document
PERL - If Statement Syntax

If statements are conditional statements used to test whether or not some condition is met and then continue executing the script. The syntax for an if statement has a specific flow to it - if(conditional_statment) { code to execute; }.

PERL - If Conditional Statements

Conditional statements may involve logical operators and usually test equality or compare one value to another. Here's a look at some common conditional statements. Remember that the code to be executed will only execute if the condition in parentheses is met.

ifs.pl:
#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$x = 7;
$y = 7;

# TESTING...ONE, TWO...TESTING
if ($x == 7) {
	print '$x is equal to 7!';
	print "<br />";
}
if (($x == 7) || ($y == 7)) {
	print '$x or $y is equal to 7!';
	print "<br />";
}
if (($x == 7) && ($y == 7)) {
	print '$x and $y are equal to 7!';
	print "<br />";
}
if.pl:
$x is equal to 7!
$x or $y is equal to 7!
$x and $y are equal to 7!

These operators are discussed thoroughly in our PERL Operators lesson.

PERL - If Else

The else statement is a perfect compliment to an if statement. The idea behind them is that if the conditional statement is not met then do this. In hypothetical, plain english, "If this is true do this, if not do this."

ifelse.pl:
#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$name = "Sarah";
$x = 5;

# IF/ELSE STATEMENTS
if ($x > 10) {
	print "$x is greater than 10!";
} else {
	print "$x is not greater than 10!";
}
print "<br />";

# STRINGS ARE A LITTLE DIFFERENT
if ($name eq "Sarah") {
	print "Hello, $name!";
} else {
	print "You are not $name!";
}
PERL - Elsif Statements

Elsif statements test another conditional statement before executing code. This way multiple conditions can be tested before the script continues.

elsif.pl:
#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$x = 5;

# PLAY THE GUESSING GAME
if ($x == 6) {
	print "X must be 6.";
}
elsif ($x == 4) {
	print "X must be 4.";
}
elsif ($x == 5) {
	print "X must be 5!";
}

We could take this example a step further, adding an else statement at the bottom. This would serve as a catch all if none of the conditions were met.

Previous                                                                                                                                                       Next

Back to Top