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?.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access