开发者

Detecting ambiguous options with Getopt::Long

开发者 https://www.devze.com 2023-03-21 03:48 出处:网络
Is there an easy way to detect ambiguous options with the Perl module Getopt::Long? For example: #!/usr/bin/env perl

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 }开发者_如何学Python,
            '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.


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.]
0

精彩评论

暂无评论...
验证码 换一张
取 消