whereas if you needed to use if-elsif-else it'd be something like:switch($number) { case 6, 12, 13, 37, 44, 68 { \&subroutine(@args); } case 1, 29, 77, 98 { \&othersub(@args); } default { sleep(1); } }
In this example I actually resorted to copy-pasting $number, having to copy-paste a piece of code over and over again is in itself a sign that what you're doing is inefficient.if(($number == 6) || ($number == 12) || ($number == 13) || ($number == + 37) || ($number == 44) || ($number == 68)) { \&subroutine(@args) } elsif(($number == 1) || ($number == 29) || ($number == 77) || ($number + == 98)) { \&othersub(@args); } else { sleep(1); }
Now, the method i personally use atm is to create a hash(or in this example above I'd even have used an array because all the case values are numerical) that would look something like this(copied from actual code I use atm):
Long story short, the main argument in favor of a switch-like statement is not having to type $wday for each and every comparison. Repetition = bad :-)my %actions = ( '001' => \&_rpl_welcome, '005' => \&_rpl_isupport, '332' => \&_rpl_topic, '333' => \&_rpl_topicdetails, '352' => \&_rpl_whoreply, '353' => \&_rpl_namreply, 'JOIN' => \&_msg_join, 'PART' => \&_msg_part, 'KICK' => \&_msg_part, 'MODE' => \&_msg_mode, 'QUIT' => \&_msg_quit, ); sub process { my($self, $line) = @_; my @text = split(/\s/, $line); if($actions{$text[1]}) { return(&{$actions{$text[1]}}($self, $line, @text)); } }
Remember rule one...
In reply to Re: using Switch;
by Forsaken
in thread using Switch;
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |