Can Getopt :: Long GetOptions throw an error if the same option occurs multiple times?
I have this getopt:
GetOptions( GetOptions ("library=s" => \@libfiles);
@libfiles = split(/,/,join(',',@libfiles));
"help" => \$help,
"input=s" => \$fileordir,
"pretty-xml:4" => \$pretty
);
Is it possible to Getopt::Long::GetOptions
find that the same option is provided on the command line multiple times? For example, I would like the following to generate an error:
perl script.pl --input=something --input=something
thank
+3
source to share
1 answer
I don't think there is a direct route, but you have two options:
-
Use an array and check after processing the parameters
#!/usr/bin/perl use warnings; use strict; use Getopt::Long; my @options; my $result = GetOptions ('option=i' => \@options); if ( @options > 1 ) { die 'Error: --option can be specified only once'; }
-
Use a subroutine and make sure the parameter is already defined
#!/usr/bin/perl use warnings; use strict; use Getopt::Long; my $option; my $result = GetOptions ( 'option=i' => sub { if ( defined $option) { die 'Error: --option can be specified only once'; } else { $option = $_[1]; } } );
In this case, you can use an exclamation mark
!
at the beginningdie
and the error will be caught and declared as a regular Getopt error (see the Getopt :: Long documentation for details)
+7
source to share