2016-05-17 81 views
1

我通过传递一些命令行选项来调用我的perl脚本。如果用户在调用脚本时没有传递必需的命令行选项,则脚本应该终止。目前我正在使用if statement进行简单检查。如果所需参数大于10,则使用If语句看起来很笨重。我只是想知道是否有更好的方法来做到这一点,而不仅仅是使用if语句。perl中的命令行选项

命令行选项:

sub startup { 
    my ($self) = @_; 

    GetOptions (
     "endpoint|e=s"   => \$self->{'endpoint'}, 
     "port|pt=s"    => \$self->{'port'}, 
     "client|c=s"    => \$self->{'client'}, 
     "client_interface|ci=s" => \$self->{'client_interface'}, 
     "origin|o=s"    => \$self->{'origin'}, 
     "origin_interface|oi=s" => \$self->{'origin_interface'}, 
     "customer_id|cid=s"  => \$self->{'customer_id'}, 
     "endpoint_id|eid=s"  => \$self->{'endpoint_id'}, 
     ) || $self->abort("Invalid command line options. 
       Valid options are endpoint,port,client,client_interface, 
    origin,origin_interface,customer_id,endpoint_id"); 

#Terminate脚本执行,如果--endpoint IP和ID - 客户和--client不会传递

if (!$self->{'endpoint'} || !$self->{'customer_id'} || !$self->{'client'}){ 
     $self->abort('[Startup] endpoint customer and client are required arguments.' 
         . 'Please provide --endpoint and --customer id and -- client '); 
    } 

命令来调用脚本:

./testframework --scriptname -- --endpoint=198.18.179.42 --port=5000 --client=1.1.1.1 --client_interface=2.2.2.2 --origin=3.3.3.3 --origin_interface= --Outertunnel=Tunnel0 --Innertunnel=Tunnel2 --customer_id=900010 --endpoint_id=2859588 
+2

我认为你对'GetOptions'的使用是正确的。然而,你有太多的参数可能表明设计问题...这些参数是否有合理的默认值?它们是否与特定的机器绑定,因此更适合作为配置文件的一部分?他们可以直接通过脚本来猜测,而不是将它们作为输入提供吗?我宁愿在这方面努力。 – eballes

+0

@eballes IP是不同的。没有什么我可以从GetOptions中摆脱出来的。我们有多个测试平台,我们希望脚本可以在所有机器上运行。 – user3587025

+2

'Getopt :: Args'可以让你指定所需的选项(oxymoron?)。 – toolic

回答

7

版本低于去除了一些clunkiness的同时提供更具体的错误消息。

my @required = qw(endpoint customer_id client); 

if (my @missing = grep { !$self->{$_} } @required) { 
    $self->abort("[Startup] Missing required arguments: @missing"); 
} 
2

一种方法是使用allList::Util

unless (all { defined $self->{$_} } qw(endpoint customer_id client)){ 
    # error 
} 

如果没有最近的List::Util版本,使用List::MoreUtils

+0

您的解决方案如何比我目前使用的解决方案更好。如果我有10个选项,我需要指定qw中的所有选项(端点customer_id客户端选项4选项5 ......选项10)这与我目前使用if stmt – user3587025

+2

@ user3587025非常相似:是的,这个答案仍然使用if语句。但是,渐进式的改进是您需要维护更少的代码,因为您不需要冗余'!$ self - > {'...'} ||'。 'Getopt :: Long'没有固有的方式来指定所需的选项。 – toolic

2

可你刚才检查,看看你有你的哈希定义键的正确号码吗?

my @options = grep { defined $self->{$_} } keys %{$self}; 
die "Missing options\n" unless @options == 10; 

或者,如果你希望你的用法说明更加明确:

for my $opt (keys %{$self}) { 
    die "Missing option --$opt\n" unless defined $self->{$opt}; 
} 
+0

该解决方案不区分必需参数和可选参数。我很惊讶它拥有最多的选票。 – tjd

+1

我将原始问题解释为暗示所有选项都是必需的。 –

+1

但即使不是,它可以很容易地修改。创建'$ self - > {required} = {}',然后改变'GetOptions'所需的参数来指向这个新的内部哈希的成员的引用,并迭代它而不是主'%{$ self} ' –