Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


elsif

$age=25;
$max=30;
$min=18;

if ($age > $max) {
        print "Too old !\n";
} elsif ($age < $min) { 
        print "Too young !\n"; 
} else { 
        print "Just right !\n"; 
}

If the first test fails, the second is evaluated. This carries on until there are no more elsif statements, or an else statement is reached. An else statement is optional, and no elsif statements should come after it. Logical, really.

There is a big difference between the above example the one below:

if ($age > $max) {
        print "Too old !\n";
} 

if ($age < $min) {
        print "Too young !\n";
}
   

If you run it, it will return the same result - in this case. However, it is Bad Programming Practice. In this case we are testing a number, but suppose we were testing a string to see if it contained R or S. It is possible that a string could contain both R and S. So it would pass both 'if' tests. Using an elsif avoids this. As soon as the first statement is true, no more elsif statements (and no else statement) are executed.

You don't need to take up a whole three lines:

print "Too old\n" if     $age > $max;
print "Too old\n" unless $age < $max;
   

I added some whitespace there for aesthetic beauty. There are other operators that you can use instead of if and unless , but that's for later on.

Incidentally, the two lines of code above do not do exactly the same thing. Consider a maximum age of 50 and input age of 50. Therefore, you should be very careful about your logic when writing code (nice obvious statement there).

For those that were wondering, Perl has no case statement. This is all explained in the FAQ, which is located at http://www.perl.com/.