Control Structures
The simplest flow of control is linear—one statement follows the next in a straight line to the end of the program. Since this is far too limiting for most situations, languages provide ways to alter the control flow.
Selection
Selection executes one set of actions out of many possible sets. The
selection control structures are if,
unless, and given.
The if statement
The if
statement checks a condition and
executes its associated block only if that condition is true. The
condition can be any expression that evaluates to a truth value.
Parentheses around the condition are optional:
if $blue {
print "True Blue.";
}The if statement can also have an unlimited number
of elsif statements that check additional
conditions when the preceding conditions are false. The final
else statement executes if all preceding
if and elsif conditions are
false:
if $blue {
print "True Blue.";
} elsif $green {
print "Green, green, green they say...";
} else {
print "Colorless green ideas sleep furiously.";
}The unless statement
The unless
statement is the logical opposite of
if. Its block executes only when the tested
condition is false:
unless $fire {
print "All's well.";
}There is no elsunless statement, though
else works with unless.
The switch statement
The switch statement selects an action by
comparing a given expression, the switch, to a
series of when statements, the cases. When a case
matches the switch, its block is executed:
given $bugblatter { when Beast::Trall { close_eyes( ); } ...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