home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeLearning Perl, 3rd EditionSearch this book

10.5. The elsif Clause

Every so often, you may need to check a number of conditional expressions, one after another, to see which one of them is true. This can be done with the if control structure's elsif clause, as in this example:

if ( ! defined $dino) {
  print "The value is undef.\n";
} elsif ($dino =~ /^-?\d+\.?$/) {
  print "The value is an integer.\n";
} elsif ($dino =~ /^-?\d*\.\d+$/) {
  print "The value is a _simple_ floating-point number.\n";
} elsif ($dino eq '') {
  print "The value is the empty string.\n";
} else {
  print "The value is the string '$dino'.\n";

Perl will test the conditional expressions one after another. When one succeeds, the corresponding block of code is executed, and then the whole control structure is done,[219] and execution goes on to the rest of the program. If none has succeeded, the else block at the end is executed. (Of course, the else clause is still optional, although in this case it's often a good idea to include it.)

[219]There's no "fall-through" to the next block, as in the "switch" structure of languages like C.

There's no limit to the number of elsif clauses, but remember that Perl has to evaluate the first ninety-nine tests before it can get to the hundredth. If you'll have more than half a dozen elsifs, you should consider whether there's a more efficient way to write it. The Perl FAQ (see the perlfaq manpage) has a number of suggestions for emulating the "case" or "switch" statements of other languages.

You may have noticed by this point that the keyword is spelled elsif, with only one e. If you write it as "elseif", with a second e, Perl will tell you that it is not the correct spelling. Why not? Because Larry says so.[220]

[220]In fact, he resists any suggestion that it even be permitted as a valid alternative spelling. "If you want to spell it with a second e, it's simple. Step 1 -- Make up your own language. Step 2 -- Make it popular." When you make your own programming language, you can spell the keywords in any way you'd like. We hope that you will decide that yours shouldn't be the first to have an "elseunless".

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.