SPUG: Hashes and subroutines

Paul Goracke paul at goracke.org
Mon Jan 5 16:19:18 PST 2009


On Jan 5, 2009, at 4:07 PM, Christopher Howard 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.

You're on the right track--use subroutine references.

------------------

my %commandMap = (
	play => \&sub1,
	that => \&sub2,
	funky => \&sub3,
	music => \&sub4,
);

if ( my $cmd = $commandMap{ $var } ) {
	$cmd->();
}
else {
	print "Unknown command '$var'\n";
}

------------------

If you have parameters to pass, the sub would be called as "$cmd- 
 >(@params)".

pg



More information about the spug-list mailing list