【问题标题】:Controlling arguments in perl with Getopt::Long使用 Getopt::Long 控制 perl 中的参数
【发布时间】:2015-07-23 19:05:38
【问题描述】:

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

我遇到的问题是我需要一个条件来说明是否使用了配置选项并指定了配置文件。我尝试计算@ARGV 中的选项,但发现如果指定了-h-c,它会导致脚本继续移动到子例程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";
}

【问题讨论】:

    标签: perl


    【解决方案1】:

    @ARGV 被 GetOptions 更改,这就是为什么它看起来是空的。无需计算参数,只需直接检查 $config_file 是否已定义。

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

    【讨论】:

    • 啊我明白了,如果定义了帮助,就完全忘记'-c'了吗?
    • 您的子帮助应该退出而不是返回,IMO。
    【解决方案2】:

    类似

    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!";
    }
    

    【讨论】:

      【解决方案3】:

      您可能还想查看Getopt::Euclid,它提供了一些扩展方式来提供选项以及使用程序文档作为命令行参数规范的一种很酷的方式。

      【讨论】:

        【解决方案4】:

        您始终可以为选项设置默认值,例如my $help = 0; my $config_file = "";,然后测试这些值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多