Right on! This is a much better way than I was considering.

"There is more than one way to do it"

Thanks,
Chris

-----Original Message-----
From: Michael Fowler [mailto:[EMAIL PROTECTED]]
Sent: Tuesday, August 14, 2001 11:20 AM
To: Schooley, Chris
Cc: '[EMAIL PROTECTED]'
Subject: Re: Command line interface


On Tue, Aug 14, 2001 at 10:54:05AM -0700, Schooley, Chris wrote:
> Sorry, I should clarify - the program itself is like shell, has its own
> commands, etc. It is intended to simulate the command line interface found
> on various Cisco devices.

Based on this, I'm going to assume you have a set of commands that you're
checking thusly:

    if ($command eq 'foo') {
        do_foo();
    } elsif ($command eq 'bar') {
        do_bar();
    } ...


What I typically do for problems like these is use a hash of hashes:

    %commands = (
        foo => {
            sub =>  \&do_foo,
        },

        bar => {
            sub =>  \&do_bar,
        },
    );

Then you simply do a lookup:

    if ($commands{$command}) {
        $commands{$command}{'sub'}->();
    } else {
        die("Unknown command name \"$command\".\n");
    }


I use a hash of hashes, instead of a hash of name => subroutine pairs, so
that I can include other meta-data along with the command.  For instance:

    %commands = (
        foo => {
            sub         =>  \&do_foo,
            arguments   =>  2,
            usage       =>  '<arg1> <arg2>',
        },

        bar => {
            sub         =>  \&do_bar,
            arguments   =>  [0, 1],
            usage       =>  '[<optional arg1>]',
        },
    );

With this, you can do things like check the number of arguments specified
for the command, and if there aren't enough, or there are too many, print
out
a usage message.


Michael
--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to