Yes, i know switch is experimental, but doing this in if's is messy, any other way for that ? like in C way of CASE ? | [reply] |
| [reply] |
Glivter: Further to haukex's reply:
In certain cases, I find ? : ternary chains (update: I've also seen them referred to as "ladders") very neat, clear, readable and maintainable, and useful:
my $result =
CONDITION1 ? EXPRESSION1 : # "if" case
CONDITION2 ? EXPRESSION2 : # "elsif" case
CONDITION3 ? EXPRESSION3 : # ditto
... # and so on...
die "no condition met... " # "else" default case
;
And, of course, you don't have to die or take any other drastic action in the default case, but simply return a default value. Your EXPRESSION can also be a side-effect-possessing do { ... } expression or subroutine call that returns a meaningful value. (A do-block or subroutine call always returns a value, but if you don't design it right, that value may be surprising.)
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |
Yes, i know switch is experimental, but doing this in if's is messy, any other way for that ? like in C way of CASE ?
I know what you mean, and I have been dreaming of a good switch implementation for Perl, but after doing a lot of research and trying a lot of different modules, I have come to accept that if-elsif-else chains are just "the" way to do it in core Perl. They also give more power in their conditions, that many of the switch implementations can't provide. To match a single value against a list of other values, there are modules such as List::Util's any and several other options. for ($value) can be used as a topicalizer. The only thing I miss is that given can return a value from its block.
| [reply] [d/l] [select] |