     Next: Multiple conditions Up: Conditionals Previous: if/else and ternary operators   Contents   Index

## if/elsif/else and switch statemements

For more complicated decision trees, the use of an if(){} elsif(){} else{} block may be needed:
```my \$age = 22;
if (\$age < 13) {
print "You aren't old enough to be a teenager";
}
elsif (\$age < 20) {
print "You are a teenager";
}
else {
print "You're too old to be a teenager";
}
```
Multiple elsif statements may be used within this block. If there are many possibilities to handle, it may be more readable to use a type of SWITCH statement - one example is as follows:
```my \$age = 22;
SWITCH: {
(\$age < 13) and do {
print "You're too young to be a teenager";
last SWITCH;
};
(\$age < 20) and do {
print "You're a teenager";
last SWITCH;
};
print "You're too old to be a teenager";
}
```
Here, we use a named block (in this example, called SWITCH), in which various conditions are tested for. If one is met, the statements within the following do{} block are executed - note the use of the last SWITCH statement to force termination of the rest of the block. The last statement within the block is a default, which will be executed if none of the previous conditions are met.

As for loops, it is possible to next if/elsif/else blocks inside of each other. Again as for loops, it is very good practice to get into the habit of indenting things. The following code

```my \$i = 3;
my \$j = 12;
my \$k = 0;
if (\$i < 30) {
if (\$j > 32) {
\$k = 22;
}
else {
\$k = 98;
}
else {
\$k = 321;
}
```
is much easier to read and to follow the logic of than
```my \$i = 3;
my \$j = 12;
my \$k;
if (\$i < 30) {
if (\$j > 32) {
\$k = 22;
}
else {
\$k = 98;
}
else {
\$k = 321;
}
```
or even
```my \$i = 3;
my \$j = 12;
my \$k;
if (\$i < 30) { if (\$j > 32) { \$k =
22; } else { \$k = 98; } else { \$k = 321;}
```
even though all three examples will mean the same to Perl.     Next: Multiple conditions Up: Conditionals Previous: if/else and ternary operators   Contents   Index