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?.
Get Perl for Web Site Management now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.