in reply to how to deal with 20 commands

The worst thing about long if-elsif-else chains is their performance, but you are talking about an interactive aplication, so you don't need to worry about performance and chained if-elsif-else's will not be so bad.

Anyway, let my suggest an alternative OO aproach: define a class for every command you support, i.e.: MyApp::Command::ls, MyApp::Command::cp, etc.

Then, in every command class define the set of methods you need, i.e. parse_args(), run(), print_output(), etc.

And then use the perl OO notation to dispatch commands:

while(read_cmd()} { eval { $cmd_name=~/^\w+/ or die "invalid command"; my $cmd_class = "MyApp::Command::$command_name"; my $cmd = eval { require $cmd_class; $cmd_class->new }; if ($@) die "unknow command $cmd_name ($@)\n"; $cmd->parse_args(@args) or die "..."; $cmd->run(@args) or die "..."; etc(); }; print $@ if $@; }
This way, adding new commands is very easy, just create new classes for them and drop them on the rigth directory. It also allows for simple code reuse via inheritance.

Replies are listed 'Best First'.
Re^2: how to deal with 20 commands
by chromatic (Archbishop) on May 24, 2005 at 00:20 UTC
    The worst thing about long if-elsif-else chains is their performance

    You can order them by expected frequency to help keep O(n/2) low, but I think the worst thing about those chains is their low maintainability.