Search code examples
perlgetopt-long

Detecting ambiguous options with Getopt::Long


Is there an easy way to detect ambiguous options with the Perl module Getopt::Long?

For example:

#!/usr/bin/env perl

# test ambiguous options

use Getopt::Long;

my $hostname = 'localhost';

GetOptions( help         => sub { print "call usage sub here\n"; exit },
            'hostname=s' => \$hostname,
          );

print "hostname == '$hostname'\n";

By default, Getopt::Long supports unique abbreviations. For non-unique abbreviations a warning is thrown and the script continues on its merry way.

./t.pl -h not_localhost

Option h is ambiguous (help, hostname)
hostname == 'localhost'

I'd like my script to die immediately on ambiguous options for immediate notification and to prevent it from running with unexpected defaults.


Solution

  • GetOptions returns false to indicate failure.

    Try:

    GetOptions( help         => sub { print "call usage sub here\n"; exit },
                'hostname=s' => \$hostname,
              )
        or die "You failed";
    

    Consider being kind to your users and using Pod::Usage. My own scripts usually look something like this:

    use warnings;
    use strict;
    use Getopt::Long;
    use Pod::Usage;
    GetOptions(...)
        or pod2usage(2);
    
    [actual code]
    
    __END__
    =head1 NAME
    myscript.pl - My Awesome Script
    =head1 SYNOPSYS
    [etc.]