in reply to how to get name of hash value itself?
What if the user provided hostname and apptype? I believe your approach will lead you to dragons.
I think you should call GetOptions twice. First call GetOptions with pass_through true to get the common parameters (user, passwd, server) and the action type (cmdName). The call GetOptions with the options required for the specified action.
Update: Here's an untested solution. I opted to not use GetOptions for the second level to avoid having to specify "-". You could use GetOptions instead of get_args if you desire more flexibility.
# Example usages: # server_admin -u USER -p PASSWD -s SERVER add_server name=NAME ipad +dr=IPADDR # server_admin -u USER -p PASSWD -s SERVER add_app type=TYPE name=NA +ME # server_admin -u USER -p PASSWD -s SERVER add_user name=NAME passwd +=PASSWD use strict; use warnings; use Getopt::Long qw( ); use File::Basename qw( basename ); my ($USERNAME, $PASSWORD, $SERVER); sub usage { my $prog = basename($0); print STDERR @_; print STDERR "usage: $prog ...\n"; print STDERR " $prog -h for more details\n"; exit(1); } sub help { my $prog = basename($0); print @_; # ...[ Provide detailed help to STDOUT. ]... exit(0); } sub get_args { my (@arg_names) = @_; my %args = map { split(/=/, $_, 2 } @ARGV; foreach (@arg_names) { if (not $args{$_}) { usage("Missing arg $_.\n"); } } my @rv = delete @args{@arg_names}; foreach (keys %args) { usage("Unknown arg $_. Accepting " . join(', ', @arg_names) . "\ +n"); } return @rv; } sub add_server { my ($name, $ipaddr) = get_args(qw( name ipaddr )); ... } sub add_app { my ($type, $name) = get_args(qw( type name )); ... } sub add_user { my ($name, $passwd) = get_args(qw( name passwd )); ... } { my %action = ( add_server => \&add_server, add_app => \&add_app, add_user => \&add_user, ); Getopt::Long::Configure(qw( posix_default )); Getopt::Long::GetOptions( 'help|h|?' => \&help, 'user|u=s' => \$USERNAME, 'passwd|p=s' => \$PASSWORD, 'server|s=s' => \$SERVER, ) or usage(); my $action = shift(@ARGV); usage() unless defined $USERNAME and defined $PASSWORD and defined $SERVER and defined $action; my $action = $actions{$action} or usage("Unknown action $action\n"); $action->(); }
|
|---|