in reply to Switch statement in Perl?
How do I create a switch or case statement?
The general answer is to write a construct like this:
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 caseinsensitive 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:
This is explained in more depth in the 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, 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.
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:
See "perlsyn/"Basic BLOCKs and Switch Statements"" for
many other examples in this style.
A totally different approach is to create a hash of function references.
Hope this helped.
CombatSquirrel.
|
|---|