【问题标题】:How to set default values for GetOpt?如何设置 GetOpt 的默认值?
【发布时间】:2014-05-15 23:26:39
【问题描述】:

我认为这很简单:

my $man = 0;
my $help = 0;
my @compList = ('abc', 'xyz');
my @actionList = ('clean', 'build');

## Parse options and print usage if there is a syntax error,
## or if usage was explicitly requested.
GetOptions('help|?' => \$help, man => \$man, 'complist:s@' => \@compList, 'action:s@' => \@actionList) or pod2usage(2);

但是,当我这样做时:

script.pl --action clean

我打印我的actionList,它只是将我的参数附加到末尾:clean build clean

【问题讨论】:

    标签: perl command-line-arguments getopt


    【解决方案1】:

    对于标量,在调用 GetOptions 时设置默认值。但是,对于数组,您需要更明确地说明您的逻辑。

    ## Parse options and print usage if there is a syntax error,
    ## or if usage was explicitly requested.
    GetOptions(
        'help|?'       => \(my $help = 0),
        'man'          => \(my $man = 0),
        'complist:s@'  => \my @compList,
        'action:s@'    => \my @actionList,
    ) or pod2usage(2);
    
    # Defaults for array
    @compList = qw(abc xyz) if !@compList;
    @actionList = qw(clean build) if !@actionList;
    

    注意,因为$help$man 只是布尔标志,实际上不需要初始化它们。除非您尝试在某处打印它们的值,否则依赖它们的默认值 undef 可以正常工作。

    【讨论】:

    • 谢谢 - 我已经做了你的改变,但现在我注意到了别的东西;数组中仅保存一个值:--complist COMPA COMPB 仅生成 COMPA
    【解决方案2】:

    您可以在GetOptions 之后设置默认值,如下所示:

    my @compList;
    GetOptions('complist:s@' => \@compList) or pod2usage(2);
    @compList = qw(abc xyz) unless @compList;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-09
      • 2011-12-31
      • 2011-07-09
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多