Search code examples
perlgetopt-long

Can Getopt::Long GetOptions generate 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 for Getopt::Long::GetOptions to detect if 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

Thanks


Solution

  • I don't think there is direct way but you have two options:

    • Use an array and check after processing the options

      #!/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 check if the option 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 beginning of the die and the error will be catched and reported as a usual Getopt error (see the documentation of Getopt::Long for the details)