SPUG: Hashes and subroutines

jerry gay jerry.gay at gmail.com
Mon Jan 5 16:26:40 PST 2009

On Mon, Jan 5, 2009 at 16:07, Christopher Howard <choward at indicium.us> wrote:
> I've got this situation where I execute a certain subroutine based on the
> value of a variable, like so:
> if($var eq 'play') { sub1() }
> elsif($var eq 'that') { sub2() }
> elsif($var eq 'funky') { sub3() }
> elsif($var eq 'music') { sub4() }
> ...
> Is there some way to do this with a hash instead? Say, the possible values
> of $var are the keys in the hash, and subroutine names (or references or
> whatever) are the values in the hash? It'd be nice if I could write out one
> long hash, and then a small piece of code to execute the appropriate
> subroutine, instead of 20+ elsif statements.
yes. this is known as a dispatch table. i use a hash reference instead
of a hash, because it's easier and more efficient for passing as a
function argument (if you need to pass the dispatch table around--i do
it all the time).

my $actions = {
  play  => \&sub1,
  that  => \&sub2,
  funky => \&sub3,
  music => \&sub4,


more advanced techniques can be found in chapter 4 of "higher order
perl", which i believe is freely available online.

More information about the spug-list mailing list