What I've got is a console programm in which the user can enter a number of commands, and commands can be added to the list using modules.
The structure holding the commands looks like this:
The wonderful code for using this looks like this:sub init_commands { # Fill %Commands hash for parsecommands # %Commands{commandname}{pattern} = # %Commands{commandname}{function} = ['modulename', [['name', numb +er of arguments]] # %Commands{commandname}{syntax} = $Commands{'log'}->{'pattern'} = '^log (.*)$'; $Commands{'log'}->{'function'} = ['', ['createlog', 1]]; $Commands{'log'}->{'syntax'} = 'log <filename> <new/append>'; $Commands{'modules saveall'}->{'pattern'} = '^modules saveall$'; $Commands{'modules saveall'}->{'function'} = ['', ['savemodules', +0]]; $Commands{'modules saveall'}->{'syntax'} = 'modules saveall'; $Commands{'modules loadall'}->{'pattern'} = '^modules loadall ([\w +\.]+)$'; $Commands{'modules loadall'}->{'function'} = ['', ['loadmodules', +1]]; $Commands{'modules loadall'}->{'syntax'} = 'modules loadall <filen +ame>'; ... and so on.. }
while( my ($command, $params) = each %Commands) { # debug("parselocalcommand: Command: $command\n"); if(substr($data, 0, length($command)) eq $command) { my $pattern = $params->{'pattern'}; if(my @res = $data =~ $pattern) { if($#+ == $params->{'function'}[1][1]) { my $answer; if($params->{'function'}[0] eq '') { $answer = &{$params->{'function'}[1][0 +]}(@res); } else { $answer = modulemethod($params->{'func +tion'}[0], $params->{'func +tion'}[1][0], @res); } if($answer) { printandprompt($answer); last; } } } else { printandprompt("Syntax: #" . $params->{'syntax +'} . "\n"); } } }
C.
In reply to Complex dispatch table by castaway
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |