Well, I just learned that switch-case is now gone :'-(
I have a bunch of sections like:
if (
$str eq 'a' ||
$str eq 'b' ||
$str eq 'c' ||
... ||
$str eq 'z') {
# do whatever
}
In theory this is slow because it compares one at a time. In PHP I could use switch like this:
switch ($str) {
case 'a':
case 'b':
case 'c':
...
case 'z':
# do whatever
}
and it's (supposedly) a lot faster because the condition is only evaluated once and then the result is compared to each case.
Perl offers up the given-when alternative, but it evaluates the condition each time, too, so I doubt that it's any faster than the if() statement. And since it's listed as experimental, I'm not sure that it'll survive for long, either.
I see that there's a Switch module, but it doesn't say anything about chaining cases:
[
metacpan.org...]
So what's a good alternative?
I know that I could do this and it would take less storage, but I doubt that a regex is faster to process:
if ($str =~ #^
a |
b |
c |
.. |
z
$#x) {
# do whatever
}
I WISH that this worked, but of course it doesn't:
if ($str eq 'a' || 'b' || 'c' || ... || 'z') {
# this reads like, "if $str equals 'a', or if 'b' exists"
# and since 'b' obviously exists, then it succeeds
}
Any other suggestions?