Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Parsing options with Getopt & Dispatch Table

by MKJ747 (Acolyte)
on Feb 17, 2011 at 15:13 UTC ( [id://888730]=perlquestion: print w/replies, xml ) Need Help??

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

I am investigating the use of the getopt method with a dispatch table to process command line arguments. I have found a lot information on the web regarding the topic, but I can't get the following simple example to work:

#!/usr/local/bin/perl # Argument options using Dispatch Tables use strict; use Getopt::Std; my %opts = (); getopts ('dhp', \%opts); %opts = ( # For each option, call appropriate subroutine. "-h" => \&help, "-d" => sub {print "\nRun DEV COMPARE\n";}, "-p" => \&PROD, "_default_" => \&default, ); sub PROD {print "\nRun Production COMPARE\n";} sub help {print "\nHelp text\n";} sub default {print "\nThat is not a valid option\n";}

The code runs without error, but does nothing when I enter any of the valid options that I defined as arguments. Any help would be appreciated. Thank you.

Replies are listed 'Best First'.
Re: Parsing options with Getopt & Dispatch Table
by toolic (Bishop) on Feb 17, 2011 at 15:24 UTC
    Getopt::Std::getopt simply fills the %opt hash with keys d, h or p (setting values to 1). You then delete all the values of the hash by your second "%opts =" assignment.

    For example, using the -d switch on your command line fills the hash with the following after the getopt call:

    $VAR1 = { 'd' => 1 };
    You then overwrite the hash entirely.

    I don't think Getopt::Std works the way you want it to. Perhaps Getopt::Long does (User defined subroutines to handle options).

Re: Parsing options with Getopt & Dispatch Table
by cjb (Friar) on Feb 17, 2011 at 15:31 UTC

    The following works with Getopt::Long

    #!/usr/local/bin/perl # Argument options using Dispatch Tables use strict; use Getopt::Long; my $result = GetOptions ( # For each option, call appropriate su +broutine. "-h" => \&help, "-d" => sub {print "\nRun DEV COMPARE\n";}, "-p" => \&PROD, ); sub PROD {print "\nRun Production COMPARE\n";} sub help {print "\nHelp text\n";}

    though you will need to add something to handle the default option

      That makes sense - Getopt::Long is working with your example. Thanks for the fast reply

      I've searched for examples of defining a default for the getoptions function - do you have any examples or could you point me to a reference? Thanks.

        Updated: Just learned that the special option 'name' "<>" can be used to designate a subroutine to handle non-option arguments (see Argument callback section in the docs). So the following is not entirely correct w.r.t. a "default option"...

        Getopt::Long has lots of configuration options that have their own defaults, but there's no option to define a default option and default value/behavior for it. You need to do that for yourself, but Getopt::Long can help. One of its default behaviors is to flag as errors “Options that are unknown, ambiguous or supplied with an invalid option value” (see the pass_through configuration option).

        So if you do nothing special, GetOptions() will tell you when you use an unknown option on the command line.

        Using cjb's sample as a start, this shows what happens when you include an unknown option on the command line:

        #!/usr/bin/env perl use 5.010; use strict; use warnings; use Getopt::Long; my $result = GetOptions ( h => \&help, d => sub {print "\nRun DEV COMPARE\n";}, p => \&PROD, ); say "result: $result"; bad_option() unless $result; say "\ncontinuing normally"; say "Doing stuff....."; say "exiting normally"; sub PROD {print "\nRun Production COMPARE\n";} sub help {print "\nHelp text\n";} sub bad_option { print "\nInvalid option detected... Quitting!!!\n"; exit 1; }
        And run like so (only defined options):
        ./pm-888730 -h -d -p Help text Run DEV COMPARE Run Production COMPARE result: 1 continuing normally Doing stuff..... exiting normally

        or thusly (one defined and one undefined option):

        ./pm-888730 -d -x Run DEV COMPARE Unknown option: x result: Invalid option detected... Quitting!!!

        Comments:

        • GetOptions() returns 1 if all's well
        • default is a keyword starting in Perl 5.10, so I don't use it here as a sub name (though it is possible to define a sub named default, you just need to get the calling syntax right... exercise for the reader).
        • Note that the behavior here is for GetOptions() to service all valid options and also to flag the error(s). If you want to trap unknown options and quit immediately, you need to move your dispatch table outside the call to GetOptions() and trap the bad option(s) before dispatching.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-24 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found