Important alert: (current site time 7/15/2013 9:05:17 PM EDT)
 

article

Create a switch or case statement

Email
Submitted on: 7/29/2000 10:57:07 PM
By: Found on the World Wide Web 
Level: Beginner
User Rating: By 2 Users
Compatibility: 5.0 (all versions), 4.0 (all versions)
Views: 26435
 
     How do I create a switch or case statement?

 
				

Briefly, there's no official case statement, because of the variety of tests possible in Perl (numeric comparison, string comparison, glob comparison, regexp 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.

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 multi-way conditional based on the type of reference stored in $whatchamacallit:

SWITCH: for (ref $whatchamacallit) {

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

/SCALAR/&& do {
print_scalar($$ref);
last SWITCH;
};

/ARRAY/ && do {
print_array(@$ref);
last SWITCH;
};

/HASH/ && do {
print_hash(%$ref);
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{$string}) {
$commands{$string}->();
} else {
print "No such command: $string\n";
} 


Other 100 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
11/1/2000 3:16:16 PMVikram Rajagopalan

Sir ,
I am from india,and just happened to go past this site.Should confess that this is ajob well done indeed.
Well, iam a starter to PEARL and so can you suggest me some books and online tutorial and material.
Thanking you and waiting eagerly for your response
(Contact me at dudleybouy@vickysmail.com)

(If this comment was disrespectful, please report it.)

 
7/20/2001 12:50:21 PMKRKeegan

If you have access to installing modules there is a switch module available at:
http://www.enstimac.fr/Perl/perl5.6.1/site_perl/5.6.1/Switch.html
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.