"be consistent" | |
PerlMonks |
Switch/case (given/when) in Perl5by Roy Johnson (Monsignor) |
on Mar 23, 2005 at 14:30 UTC ( [id://441778]=perlmeditation: print w/replies, xml ) | Need Help?? |
Occasionally, people lament that Perl has no switch/case statement like C. Perl6 has given/when, which goes several steps beyond the simple switch by handling arbitrary conditions, rather than simple equivalence.
So what does it buy you over if-else? Not a lot, in my experience. You can save some keystrokes by not retyping what you're matching against, and sometimes the ability to control whether things "fall through" -- matching multiple cases -- can come in handy. Of course, we are not entirely without alternatives in Perl5. For simple multi-candidate equality testing without defaulting or fall-through, you can use a hash: Grep is a natural tool for multi-way matching, and you can set it up to do fall-through and defaulting, though you do have to work at it: Clearly you could encapsulate this in a function that takes your given and the list of condition-then(-break) sub pairs/triplets. Still not pretty enough? Then maybe I can interest you in something that looks a lot like Perl6's given (even though I think it should have been called "consider" for better reading): Given can only consider a scalar, but otherwise it's pretty comparable to the Perl6 critter, eh? Update: added isit sub, to provide implicit eq check against $_. Writing when {$_ eq 'something'} for a lot of cases would get pretty old. Caution: Contents may have been coded under pressure.
Back to
Meditations
|
|