FAQ 7.22 How do I create a switch or case statement?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.


7.22: How do I create a switch or case statement?

    This is explained in more depth in the perlsyn. Briefly, there's no
    official case statement, because of the variety of tests possible in
    Perl (numeric comparison, string comparison, glob comparison, regex
    matching, overloaded comparisons, ...). Larry couldn't decide how best
    to do this, so he left it out, even though it's been on the wish list
    since perl1.

    Starting from Perl 5.8 to get switch and case one can use the Switch
    extension and say:

            use Switch;

    after which one has switch and case. It is not as fast as it could be
    because it's not really part of the language (it's done using source
    filters) but it is available, and it's very flexible.

    But if one wants to use pure Perl, the general answer is to write a
    construct like this:

        for ($variable_to_test) {
            if    (/pat1/)  { }     # do something
            elsif (/pat2/)  { }     # do something else
            elsif (/pat3/)  { }     # do something else
            else            { }     # default

    Here's a simple example of a switch based on pattern matching, this time
    lined up in a way to make it look more like a switch statement. We'll do
    a multiway conditional based on the type of reference stored in

        SWITCH: for (ref $whatchamacallit) {

            /^$/            && die "not a reference";

            /SCALAR/        && do {
                                    last SWITCH;

            /ARRAY/         && do {
                                    last SWITCH;

            /HASH/          && do {
                                    last SWITCH;

            /CODE/          && do {
                                    warn "can't print function ref";
                                    last SWITCH;

            # DEFAULT

            warn "User defined type skipped";


    See "perlsyn/"Basic BLOCKs and Switch Statements"" for many other
    examples in this style.

    Sometimes you should change the positions of the constant and the
    variable. For example, let's say you wanted to test which of many
    answers you were given, but in a case-insensitive way that also allows
    abbreviations. You can use the following technique if the strings all
    start with different characters or if you want to arrange the matches so
    that one takes precedence over another, as "SEND" has precedence over
    "STOP" here:

        chomp($answer = <>);
        if    ("SEND"  =~ /^\Q$answer/i) { print "Action is send\n"  }
        elsif ("STOP"  =~ /^\Q$answer/i) { print "Action is stop\n"  }
        elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
        elsif ("LIST"  =~ /^\Q$answer/i) { print "Action is list\n"  }
        elsif ("EDIT"  =~ /^\Q$answer/i) { print "Action is edit\n"  }

    A totally different approach is to create a hash of function references.

        my %commands = (
            "happy" => \&joy,
            "sad",  => \&sullen,
            "done"  => sub { die "See ya!" },
            "mad"   => \&angry,

        print "How are you? ";
        chomp($string = <STDIN>);
        if ($commands) {
        } else {
            print "No such command: $string\n";


Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.


    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

Site Timeline