2009-06-04 48 views
1

我被迫(由工程政策)使用Getopt::Euclid解析 参数我的Perl程序。我有三个参数,foo,bar和blah。如何使用Getopt :: Euclid检测组合参数错误?

它是合法的没有这些,并使用其他参数,而不是。

如果foo存在而不是正好存在一个bar或blah,则应该存在 ,如果存在bar或blah,则必须存在foo。

阅读CPAN文档后,我看不出有什么办法让欧几里德 检测和强制执行这些限制。如果Euclid可以执行这些限制,我想了解如何。

否则,我会自己检测条件,但想要哄 Euclid生成--help输出,如果违反条件的话, 但是不能从程序中看到如何操作。想法?

回答

1

嗯,它看起来像您可以使用您选择的选项部分,它不会抱怨,如果它们不存在,但我没有看到任何逻辑,使相关的选项,所以你必须编写你自己逻辑。我还没有看到,会打印出任何使用功能,但你总是说

system $^X, $0, "--help"; 

将运行使用相同的解释($^X)脚本($0),它与调用,并通过它的论点--help。这是丑陋的,但它应该工作。

=head1 OPTIONS 

=over 

=item --foo <foo> --bar <bar> | --foo <foo> --baz <baz> 

然后使用$ARGV{'--foo'}{'foo'},要么$ARGV{'--foo'}{'bar'}$ARGV{'--foo'}{'baz'}

#!/usr/bin/perl 

use strict; 
use warnings; 

use Getopt::Euclid; 

sub usage { 
    my $message = shift; 
    print "$message\n\n"; 
    system $^X, $0, "--help"; 
} 

if (keys %ARGV) { 
    unless (exists $ARGV{'--foo'}) { 
     usage "--foo must be present if --bar or --blah is present"; 
     exit -1; 
    } 

    if ($ARGV{'--bar'} and $ARGV{'--blah'}) { 
     usage "only one of --bar or --blah may be present"; 
     exit -1; 
    } 
} 

unless ($ARGV{'--foo'}) { 
    print "Doing nothing\n"; 
    exit 0; 
} 

print "fooing bar\n" if $ARGV{'--bar'}; 
print "fooing blah\n" if $ARGV{'--blah'}; 


__END__ 

=head1 NAME 

foo.pl - foo the bar 

=head1 VERSION 

1.0 

=head1 usage 

    foo.pl [options] 

=head1 OPTIONS 

=over 

=item --foo 

do the foo (requires --bar or --blah) 

=item --bar 

what to do the foo to (requires --foo) 

=item --blah 

what to do the foo to (requires --foo) 

=item --help 

=back 

=head1 AUTHOR 

Chas. J. Owens IV 

=head1 BUGS 

Hopefully none 

=head1 COPYRIGHT 

Copyright (c) 2009, Chas. J. Owens IV. All Rights Reserved. 
This module is free software. It may be used, redistributed 
and/or modified under the terms of the Perl Artistic License 
(see http://www.perl.com/perl/misc/Artistic.html) 
0

像你想假装它只是一个选项看起来对我来说(没用过摹:: E和没有测试)。

我想我假设他们都有争论;你没有说清楚。

更新:似乎工作,但它给了误导性的错误消息,如果你省略酒吧或巴兹或同时指定。如果没有开关带参数,你可以这样做:

=item --foo --bar | --foo --baz 

=for Euclid 
    false: --foo --baz 

$ARGV{'--foo'}将成为巴真,假的巴兹,如果既不是不存在的。

从长远来看,你可能会更好发送的Getopt ::欧几里得笔者一个补丁,允许这样的:

=item --foo 

=for Euclid 
    requires: --bar | --baz 

=item --bar 

=for Euclid 
    requires: --foo 

=item --baz 

=for Euclid 
    requires: --foo 

因此,如果指定了不一致的选项,它可以产生有意义的错误消息。

0

怎么样的Getopt ::欧几里得手册中的“占位符约束”部分中描述的功能?具体地,这种形式:

PLACEHOLDER.type: TYPE [, EXPRESSION_INVOLVING(PLACEHOLDER)] 

EXPRESSION_INVOLVING可以是任意的perl表达,相信。它甚至不必涉及选项本身。所以bar和blah的约束表达式都可以检查另一个不存在,并且foo确实存在。

唯一的问题是,这可能会强加一个顺序依赖于你的论点。这将是合法的:--foo --bar;但是这不会:--bar --foo,因为当阅读--bar参数时,Euclid不知道--foo,所以它呱呱叫。所以如果你走这条路线,一定要为--bar的这个效果指定一个错误信息。

0

您可以使用getopt :: Euclid版本0.2.4(2011年6月发布)以来的'exclude'关键字指定互斥的参数。