Tinkering with Perl

(Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  35  36  37  38  39  40  41  42  43  44  Next  Skip Forward
Printer-Friendly Version

If-then-else chains

There is one more step to be taken with if-then-else. That is demonstrated by the following segment of code:

if ($Pet == "dog")
    {
    print "Arf, arf!\n";
    }
elsif ($Pet == "cat")
    {
    print "Purr, purr!\n";
    }
elsif ($Pet == "goldfish")
    {
    print "Splish, splash!\n";
    }
else
    {
    print "I don't know what sound the pet makes.\n";
    }

Sometimes, you have more than two choices to deal with -- there are more than two (or three) possibilities for a pet. An if-then-else chain is ideal for the following; the program checks if the first condition is true, and if the first condition is false, it checks if the second condition is true, and so on and so forth. The general syntax is:

if (first conditional clause)
    {
    code to be executed
    if first conditional clause is true
    }
elsif (second conditional clause)
    {
    code to be executed if first
    conditional clause is false, but
    second conditional clause is true
    }
...
elsif (last conditional clause)
    {
    code to be executed if all but the
    last conditional clauses are false, but
    the last conditional clause is true
    }
else
    {
    code to be executed if none of the
    conditional clauses are true.
    }

The final else is optional, but recommended.

See also:

Statements - Arithmetic - Flow control - Blocks - Conditional clauses - If-then - If-then-else

Tinkering with Perl is a free book that provides an introduction to programming in Perl, as well as a basic reference for things like foreach in Perl, if-then, and if-then-else, in addition to providing a glossary where you can find definitions for concatenate and other terms.

Tinkering with Perl may be one of the most popular offerings on this site, but it's not the only attraction. You can read a tongue-in-cheek Game Review: Meatspace, read an even more offbeat customer service survey (whether or not you actually fill it out), and spend a few minutes wishing your boss would read, The Administrator Who Cried, "Important!" (Not to mention that there are other things you can read here besides tech stuff, from Janra Ball: The Headache to The Spectacles.)

Read more...

Top

(Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  35  36  37  38  39  40  41  42  43  44  Next  Skip Forward
Printer-Friendly Version