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

I'm using GetOptions but my non-option callback routine isn't being called. What's wrong with my code, wise monks?
my $convert = 0; my $export = 0; my $exportfile = ""; ... GetOptions( "convert" => \$convert, "export" => \$export, "exportfile=s" => \$exportfile, "<>" => \&badarg, ); ... sub badarg { my $badparm = $_[0]; print"badarg $badparm\n"; }
The GetOptions call prints "unknown option: blah" but badarg() isn't called. If the "<>" line is removed, then GetOptions still seems to swallow all the option, rather than leaving unmatched options in @ARGV.
("This is perl, v5.8.4 built for MSWin32-x86-multi-thread" ActivePerl Build 810)

Edit: after jimbojones' hint about pass_though, I find that the callback works iff pass_through is used! (but NOT permute) thanks all!

Replies are listed 'Best First'.
Re: GetOptions non-option callback
by Tanktalus (Canon) on Feb 24, 2005 at 20:11 UTC

    According to Getopt::Long, in order for this to work, you need to configure it for "permute". Something like:

    Getopt::Long::Configure("permute");
    Have you done this?

      Thanks for that: embarrassingly I had not used permute, despite seeing it in the docs. But having added it has made no difference: the sub still isn't called (though @ARGV is empty after GetOptions) and "Unknown option: " is still printed to console.
Re: GetOptions non-option callback
by jimbojones (Friar) on Feb 24, 2005 at 20:30 UTC
    If you want to leave unmatched options in @ARGV, use

    Getopt::Long::Configure( "pass_through" );
    or use the "--" construction.

    -j
      well, I'd prefer to catch bad options but maybe I should leave them in @ARGV and parse that after GetOptions, since my callback isn't working.

      Edit: pass_though seems to enable the callback functionality (despite the docs) so I'll just use that. Thanks!
Re: GetOptions non-option callback
by jimbojones (Friar) on Feb 24, 2005 at 21:12 UTC
    Hi

    I ran your code with the permute option and it worked for me. Can you post your command line call?

    use Getopt::Long; Getopt::Long::Configure("permute"); my $export = 0; my $exportfile = ""; GetOptions( "convert" => \$convert, "export" => \$export, "exportfile=s" => \$exportfile, "<>" => \&badarg, ); sub badarg { my $badparm = $_[0]; print"badarg $badparm\n"; } __DATA__ >get_opt.pl --convert --export --exportfile temp.txt blah blah badarg blah badarg blah
    this was under both AS 5.6.1 and 5.8.4

    - j