2011-03-13 28 views
2

我正在嘗試使用Getopt::Long將命令行參數添加到我的腳本中(見下文)。我遇到的問題與執行不同事情的多個命令有關。例如,我有一個選項標誌,用於設置配置文件與腳本一起使用,選項爲-c [config_path],我也有-h以獲得幫助。使用Getopt :: Long控制perl中的參數

我遇到的問題是我需要一個條件,指出是否已使用配置選項並指定了配置文件。我試着計算@ARGV中的選項,但發現如果指定-h-c,則會導致腳本無論如何移動到子例程load_config。因爲在@ARGV中找到2個參數時,會在下面的代碼中看到它觸發子例程。

我該如何解決這個問題?至少在我的頭上,指定-h-c在同一時間sorta相互矛盾。有沒有辦法讓它這樣只有「信息性命令」,如幫助不能用「操作命令」如-c執行?有沒有辦法讓我得到已經通過的命令列表?我嘗試打印@ARGV的內容,但即使指定了命令參數,也沒有任何內容。

#!/usr/bin/perl 
use strict; 
use warnings; 
use Getopt::Long; 
use Term::ANSIColor; 
use XML::Simple; 
use Net::Ping; 
use Net::OpenSSH; 
use Data::Dumper; 

# Create a new hash to copy XML::Simple configuration file data into 
my %config_file; 

# Clear the screen and diplay version information 
system ("clear"); 
print "Solignis's Backup script v0.8 for ESX\\ESX(i) 4.0+\n"; 
print "Type -h or --help for options\n\n"; 

# Create a new XML::Simple object 
my $xml_obj = XML::Simple->new(); 

# Create a new Net::Ping object 
my $ping_obj = Net::Ping->new(); 

my $config_file; 

my $argcnt = $#ARGV + 1; 

GetOptions('h|help' => \&help, 
     'c|config=s' => \$config_file 
    ); 

if ($argcnt == 0) { 
    print "You must supply a config to be used\n"; 
} elsif ($argcnt == 2) { 
    if (! -e $config_file) { 
     print color 'red'; 
     print "Configuration file not found!\n"; 
     print color 'reset'; 
     print "\n"; 
     die "Script Halted\n"; 
    } else { 
     load_config(); 
    } 
} 

sub load_config { 

    print color 'green'; 
    print "$config_file loaded\n"; 
    print color 'reset'; 

    my $xml_file = $xml_obj->XMLin("$config_file", 
        SuppressEmpty => 1); 

    foreach my $key (keys %$xml_file) { 
      $config_file{$key} = $xml_file->{$key}; 
    } 

    print Dumper (\%config_file); 
} 

sub help { 
    print "Usage: backup.pl -c [config file]\n"; 
} 

回答

8

@ARGV由GetOptions改變,這就是爲什麼它似乎是空的。而不是計算參數,直接檢查是否定義了$config_file

順便說一句,國際海事組織沒有必要試圖排除-c-h一起使用。通常情況下,「幫助」只是打印幫助文本並退出而不採取任何其他行動,首先檢查並確定是否提供-c

+0

啊我明白了,如果幫助被定義了,只要忘了'-c'? – ianc1215

+0

你的子幫助應該退出而不是返回,國際海事組織。 – Anomie

3

喜歡的東西

my $help; 
my $config_file; 

GetOptions('h|help' => \$help, 
    'c|config=s' => \$config_file 
); 

if (defined $help) { 
    help(); 
} elsif (defined $config_file) { 
    ...; 
} else { 
    die "No arguments!"; 
} 
0

您可能還想看看Getopt::Euclid,它提供了一些擴展的方法來提供選項和一個很酷的使用程序文檔作爲命令行參數規範的方法。

0

您可以隨時爲選項設置默認值,例如my $help = 0; my $config_file = "";,然後測試這些值。