perlfaq nodetype
faq_monk
<P>
This is explained in more depth in the [perlman:perlsyn|the perlsyn manpage]. 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.
<P>
The general answer is to write a construct like this:
<P>
<PRE> for ($variable_to_test) {
if (/pat1/) { } # do something
elsif (/pat2/) { } # do something else
elsif (/pat3/) { } # do something else
else { } # default
}
</PRE>
<P>
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:
<P>
<PRE> SWITCH: for (ref $whatchamacallit) {
</PRE>
<P>
<PRE> /^$/ && die "not a reference";
</PRE>
<P>
<PRE> /SCALAR/ && do {
print_scalar($$ref);
last SWITCH;
};
</PRE>
<P>
<PRE> /ARRAY/ && do {
print_array(@$ref);
last SWITCH;
};
</PRE>
<P>
<PRE> /HASH/ && do {
print_hash(%$ref);
last SWITCH;
};
</PRE>
<P>
<PRE> /CODE/ && do {
warn "can't print function ref";
last SWITCH;
};
</PRE>
<P>
<PRE> # DEFAULT
</PRE>
<P>
<PRE> warn "User defined type skipped";
</PRE>
<P>
<PRE> }
</PRE>
<P>
See <CODE>perlsyn/"Basic BLOCKs and Switch Statements"</CODE> for many other examples in this style.
<P>
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 <CODE>"SEND"</CODE> has precedence over
<CODE>"STOP"</CODE> here:
<P>
<PRE> 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" }
</PRE>
<P>
<FONT SIZE=-1>A</FONT> totally different approach is to create a hash of
function references.
<P>
<PRE> my %commands = (
"happy" => \&joy,
"sad", => \&sullen,
"done" => sub { die "See ya!" },
"mad" => \&angry,
);
</PRE>
<P>
<PRE> print "How are you? ";
chomp($string = <STDIN>);
if ($commands{$string}) {
$commands{$string}->();
} else {
print "No such command: $string\n";
}
</PRE>
<P>