【问题标题】:Can Getopt::Long GetOptions generate an error if the same option occurs multiple times?如果同一选项多次出现,Getopt::Long GetOptions 会产生错误吗?
【发布时间】:2012-04-06 14:44:17
【问题描述】:

我有这个 getopt:

GetOptions(  GetOptions ("library=s" => \@libfiles);
    @libfiles = split(/,/,join(',',@libfiles));
     "help" => \$help,
     "input=s" => \$fileordir,
     "pretty-xml:4" => \$pretty
);

Getopt::Long::GetOptions 是否可以检测是否在命令行上多次提供了相同的选项?例如,我希望以下内容生成错误:

perl script.pl --input=something --input=something

谢谢

【问题讨论】:

    标签: perl getopt-long


    【解决方案1】:

    我认为没有直接的方法,但您有两种选择:

    • 使用数组并在处理选项后检查

      #!/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';
      }
      
    • 使用子程序并检查选项是否已定义

      #!/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]; 
              }
          }
      );
      

      在这种情况下,您可以在die 的开头使用感叹号!,该错误将被捕获并报告为通常的Getopt错误(有关详细信息,请参阅documentation of Getopt::Long

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多