SPUG: Hashes and subroutines

Jack Foy jack at foys.net
Tue Jan 6 20:16:20 PST 2009


Paul Goracke wrote:
> 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)".

That's close to how I would have written it, too.  What about this?


sub runCommand {
	my $command = shift;
	my $rArgs = shift;	# or use @_, but see note 1

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

	# See note 2
	my $rAction = $actions{$command}
		or return LogError ("Unknown command '$var'");

	return &$rAction ($rArgs);
}

# Note 1: I avoid using @_ directly.  This both makes the code easier to
# read by making routine arguments explicit, and avoids accidental
# aliasing.

# Note 2: We use a logging library whose Log() variants are guaranteed
# to return undef.  That makes this kind of idiom easy to use.


-- 
Jack Foy <jack at foys.net>


More information about the spug-list mailing list