使用Getopt :: Long控制perl中的参数

ian*_*215 2 perl

我试图使用Getopt :: Long添加命令行参数到我的脚本(见下文).我遇到的问题与多个执行不同操作的命令有关.例如,我有一个选项标志,用于设置配置文件以与选项所使用的脚本一起使用,-c [config_path]我也可以-h寻求帮助.

我遇到的问题是我需要一个条件,说明是否已使用配置选项并指定了配置文件.我试着在计数的选项@ARGV,但如果发现-h-c被specifed它会导致脚本上移到子程序load_config反正.因为如下面的代码所示,当在@ARGV其中找到2个参数时会触发子例程.

我能以什么方式解决这个问题?至少在我的头脑中指定-h并且-c同时又互相矛盾.有没有办法让它变成只有像"操作命令"那样的"信息命令"才能执行-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";
}
Run Code Online (Sandbox Code Playgroud)

Ano*_*mie 8

GetOptions改变了@ARGV,这就是为什么它似乎是空的.而不是计算参数,只需直接检查是否$config_file已定义.

顺便说一句,IMO没有必要尝试排除-c使用-h.通常情况下,"帮助"只打印帮助文本并退出而不采取任何其他操作,首先检查它,无论是否-c提供都无关紧要.