Guideline IF1: Avoid multiple if-then-else with jump table switching
For a choice of integers or other simple types which permit it, use a switch
statement.
For a choice of more complex data types (strings, etc.) use a jump table, allowing you to set up your selections during program initialization (possibly even in a configuration file!).
While Perl does not have an official switch
statement, the perlsyn manual page, Basic BLOCKs and Switch Statements section, illustrates not one, not two, but nine different ways to achieve the same result.
They are presented quite elegantly, so I won't repeat them here.
At the very end of the section, it mentions, "You might also consider writing a hash of subroutine references instead of synthesizing a switch statement."
But it does not provide such an example, so I've provided it here:
sub pick { my ($select, $val) = @_; if ($select eq "abc") { doTaskA($val); } elsif ($select eq "def") { doTaskB($val); } elsif ($select eq "ghi") { doTaskC($val); } elsif ($select eq "jkl") { doTaskD($val); } elsif ($select eq "mno") { doTaskE($val); } } sub doTaskB { # stub for testing print "got value ".shift()."\n"; } pick("def", 25); # test invocation
my $JUMP_TABLE = { abc => \&doTaskA, def => \&doTaskB, ghi => \&doTaskC, jkl => \&doTaskD, mno => \&doTaskE }; sub pick { my ($select, $val) = @_; &{$JUMP_TABLE->{$select}}($val); } sub doTaskB { # stub for testing print "got value ".shift()."\n"; } pick("def", 25); # test invocation