2012-04-06 55 views
3

我有這樣的getopt:Can Getopt :: Long如果同一選項多次出現,GetOptions會產生錯誤?

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 

感謝

回答

7

我不認爲有直接的方式,但你有兩種選擇:

  • 使用數組並在處理後檢查選項

    #!/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的細節)

相關問題