Search code examples
perlgetopt-long

Recognize unknown options in Getopt::Long


How can you recognize unknown options using Getopt::Long?

I tried <>, but it did not work as expected. Consider:

use Modern::Perl;
use Getopt::Long;

my $help='';
GetOptions ('help' => \$help,'<>' => \&usage);
usage() if $help;

usage() if @ARGV != 1;

my $fn=pop;

say "FileName: $fn";

sub usage {
    say "Unknown option: @_" if ( @_ );
    say "Usage: $0 <filename>";
    say "       $0 --help";
    say "";
    exit
}

I would like to print Unknown option only if there is an unrecognized option (in this case, anything other than --help). But, now it thinks the filename is an unrecognized option.


Solution

  • Call your usage function if GetOptions fails. Getopt::Long will print Unknown option for you (to STDERR):

    use Modern::Perl;
    use Getopt::Long;
    
    my $help='';
    GetOptions ('help' => \$help) or usage();
    usage() if $help;
    
    usage() if @ARGV != 1;
    
    my $fn=pop;
    
    say "FileName: $fn";
    
    sub usage {
        say "Usage: $0 <filename>";
        say "       $0 --help";
        say "";
        exit
    }