Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

parsing @ARGV with Getopt::Long multiple times

by bliako (Monsignor)
on Apr 01, 2020 at 12:11 UTC ( [id://11114902]=perlquestion: print w/replies, xml ) Need Help??

bliako has asked for the wisdom of the Perl Monks concerning the following question:

I think I need to call Getopt::Long twice. The first time I take from user the name of the configuration file (say --config abc). Then I read the file, and create a hash of parameters.

Then, as a 2nd pass, I need to overwrite any of these parameters in the config with user-specified values from the command line for this particular run. The config hash is too nested, so I just can't pass it to Getopt (like it is mentioned in the doc).

And so I resort to this:

use Getopt::Long; my $configfile; my @ARGVcopy = @ARGV; # because 1st pass eats all options in @ARGV!! { local $SIG{__WARN__} = sub { }; # don't complain when see options re +levant to the 2nd pass Getopt::Long::GetOptions('--config=s', \$configfile); # no check! it + will fail } die "config needed" unless $configfile; my $confighash = parse_configfile($configfile); # 2nd pass with restored ARGV @ARGV = @ARGVcopy; Getopt::Long::GetOptions( 'config=s' => \my $dummy, #<<<< this belongs to 1st phase but is stil +l in cmdline (@ARGV) '--max-value=i' => \$confighash->{'a'}->{'b'}->{'max-value'}, ) or die "error cmd line params";

Is there a more elegant way? I mean 2 passes, and then the $dummy? Modifying @ARGV between 1st pass and 2nd pass is not acceptable as a new can of worms will be opened (edit: or is it a question of 2 shifts?).

bw, bliako

Replies are listed 'Best First'.
Re: parsing @ARGV with Getopt::Long multiple times
by Corion (Patriarch) on Apr 01, 2020 at 12:14 UTC

    I think you want the pass_through option to the first GetOptions() call. This will collect only the things it knows from @ARGV and leave the rest there.

      Thanks that worked. Sorry I missed it when reading that doc.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11114902]
Approved by talexb
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2024-04-23 08:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found