"Using X, I want to do Y." But X doesn't do Y - it does X.
Can you explain why you want to do this rather than just passing in the entire hash? Obviously, you'll need to massage the hash a bit to pass in - since X doesn't do Z either.
my @getoptions_args = keys %test; my %opts = map { (my $o = $_) =~ s/[=:|\!].*$//; $o => $test{$_} } @ge +toptions_args; GetOptions(\%opts, @getoptions_args); %test = %opts;
This will set up the options for GetOptions properly, and put everything back in the originating hash. I have changed the keys permanently - this makes things easier, in fact, since you only need to look up "option1" rather than "option1=s". You can also use GetOpt::Long's aliasing ability - by using, for example, "option1|o=s", GetOpt::Long will allow --option1 string or -o string and put the string in the same place for both, but your code only needs to use option1.
This is, in fact, very very similar to the commandline options module I use at work where I "accept" a bunch of parameters from all the other modules, then I parse the arguments, putting them in a global hash, and everyone can query the parameters that way. Each module passes in what you have there - the full option for GetOptions with the = or ! or whatever sigil describing the data type, including aliases, etc. And then I massage that and pass it into GetOpt::Long. Afterwards, I do post-parsing validation, and then return control back to the main program. I do the validation by using the value passed in - I actually use something like this:
And then the wrapper module uses all that info for --help (which is "help|?"), or validating values, or assigning defaults when they aren't given. It's one of the strengths of our environment ... and I probably need to find a way to CPANise it. :-)$cmdlineparser->accept( 'option1=s' => { default => sub { # derive some default }, validate => sub { # validate @_ is ok. }, help => 'Option1 does blah blah blah fooseball', }, );
Update: Anyone who has a good name for such a module, please respond - either by adding a comment here or via /msg. I'm kind of at a loss. I've tossed out G::L::Simple (it's not - Getopt::Long is already pretty simple), and even G::L::Singleton and G::L::Wrapper I'm not too keen on. It does more than just validation, optionally can help with usage, etc. - lots of stuff. I suppose it's kind of a Getopts::Long::Framework sorta ... any other ideas?
In reply to Re: Hash and GetOptions (Getopt::Long)
by Tanktalus
in thread Hash and GetOptions (Getopt::Long)
by Ace128
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |