Phoenix.pm: Parameter parser

David A. Sinck phx-pm-list at grueslayer.com
Wed Nov 27 07:54:12 CST 2002



\_ SMTP quoth Doug Miles on 11/26/2002 14:46 as having spake thusly:
\_
\_ Doug Miles wrote:
\_ > Hey all,
\_ > 
\_ > I just implemented a parser that takes something like this:
\_ > 
\_ > command param1 param2="value2" param3="value3 \"foo\""
\_ > 
\_ > and puts the parameters and values into a hash.  The value for param1 
\_ > would be "1".  I'm not sure I implemented it the best way, though.  I 
\_ > thought I'd get some ideas from you folks to get a different 
\_ > perspective.  I'll post what I did after I get some responses.  I don't 
\_ > want to contaminate your thinking. :)

What about defaults?  I've recently decided to try a hash config of

my %args = (
	    'h' => {'short' => 'this help',
		   },
	    'i' => {'short' => 'ignore password descrepancies',
		   },
	    'd' => {'short' => 'what to debug',
		    'arg' => 's',
		   },
	    'b' => {'short' => 'database to dump',
		    'arg' => 's',
		    'default' => 'mysql',
		   },
	    ....
	    );

sub print_help
{
  [...]
  my $args = join ("\n", map {
    sprintf "-%s %s: %s", $_, (($args{$_}{arg}) ? "<$args{$_}{arg}>" : '   '),
      $args{$_}{short}
			    } sort keys %args);

  print <<EOHELP;
Usage: $0 [args]
$args

Version: $revinfo
EOHELP
  ;

}

my $argstring = join('',map {$_ . (($args{$_}{arg}) ? ':' : '')} keys %args);
&getopts($argstring, \%opt);

and then later do $opt{$arg} ||= $args{$arg}{default} by hand (I
haven't yet had enough of them to bake the formal map {} invocation
for defaults.)


David



More information about the Phoenix-pm mailing list