Reputation: 40738
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.
Upvotes: 2
Views: 6300
Reputation: 35198
Start using pod documentation as the core modules Getopt::Long
and Pod::Usage
work very well together. Can get the behavior you want without having to create helper methods to accomplish it:
Here's an example script:
#!/usr/bin/perl
use File::Basename qw(basename);
use Getopt::Long qw(GetOptions);
use Pod::Usage qw(pod2usage);
use Readonly;
use version;
use strict;
use warnings;
Readonly my $VERSION => qv('0.0.1');
Readonly my $EXE => basename($0);
GetOptions(
'version' => \my $version,
'usage' => \my $usage,
'help|?' => \my $help,
'man' => \my $man,
) or pod2usage(-verbose => 0);
pod2usage(-verbose => 0) if $usage;
pod2usage(-verbose => 1) if $help;
pod2usage(-verbose => 2) if $man;
if ($version) {
print "$EXE v$VERSION\n";
exit;
}
## Check for File
pod2usage("$EXE: No filename specified.\n") unless @ARGV;
my $file = $ARGV[0];
pod2usage("$EXE: $file is a directory.\n") if -d $file;
pod2usage("$EXE: $file is not writable.\n") if !-w $file;
#....
print "Hello World\n";
#....
1;
__END__
=head1 NAME
hello.pl - Mirrors a script using pod
=head1 SYNOPSIS
./hello.pl [FILE]
=head1 OPTIONS
=over 4
=item --version
Print the version information
=item --usage
Print the usage line of this summary
=item --help
Print this summary.
=item --man
Print the complete manpage
=back
=head1 DESCRIPTION
Sometimes a programmer just enjoys a bit of documentation.
They can't help themselves, it makes them feel accomplished.
=head1 AUTHOR
Written by A Simple Coder
Output:
>perl hello.pl --test
Unknown option: test
Usage:
./hello.pl [FILE]
Upvotes: 4
Reputation: 62037
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
}
Upvotes: 4