O'Reilly logo

Perl for Web Site Management by John Callender

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

if Statements

The next section of the script introduces another common programming construct: the if statement. An if statement is similar to the foreach loop we just looked at, in that it allows you to do something special with a block of code. An if statement allows you to make execution of the code conditional upon the outcome of a test.

Another term for an if statement is a conditional statement. Conditional statements in Perl look like this:

if (test) {
    do something...
}

Other, fancier versions of Perl’s conditional statements look like this:

if (test) {
    do something...
} else {
    do something else...
}

or this:

if (test) {
    do something...
} elsif (another test) {
    do something else...
} elsif (yet another test) {
    do some other something else...
} else {
    do still some other something else...
}

and so on. The trickiest part for beginners (besides getting all those curly braces in the right place) is understanding how Perl evaluates those (test) statements for “truth.” To understand that, see True or False?.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required