[Melbourne-pm] Perl best practices: script actions based on a command line argument

Toby Corkindale toby.corkindale at rea-group.com
Thu Jan 31 22:04:48 PST 2008


Daniel Pittman wrote:
> G'day.
> 
> I semi-regularly end up writing small scripts that do little jobs for
> myself, such as performing various DNS checks, interfacing to billing
> systems and the like.
> 
> Generally these end up as a single script that handles half a dozen
> closely related but mostly independent functions, such as:
> 
>      dns mx ...         # check MX details for a domain
>      dns ns ...         # check NS details for a domain
> 
> I typically implement this as a bunch of supporting code and libraries,
> and a command wrapper that read the first command line argument and
> dispatches to a function based on it.
> 
> This being Perl there are a lot of ways to do that, all of which are
> a bit ugly (in my opinion), such as a cascade of if ($blah eq 'foo')
> statements or a hash full of function refs...
> 
> 
> So, what is the general consensus on the best way to do this -- what is
> the nicest way to dispatch to the various command handlers based on a
> command line argument?

How about:
package My::Commands;
use base 'My::Dispatcher';

sub pull : Dispatchable {
# pull stuff
}

sub push : Dispatchable {
# push stuff
}


and then in your main code you do:
$pkg->dispatch($ARGV[0]);


where My::Dispatcher needs to add an attribute handler for Dispatchable, 
so as to list those methods as valid things to be called.


More information about the Melbourne-pm mailing list