我可以在perl中使用Getopt :: Long lib绑定两个不同的输入标志吗?

问题描述

让我们举一个简单的例子:我想在脚本中输入以下内容

[
{foo => date_1},{foo2=> date_2},{foo3=> undef},# there was no input
... # probably more in the future
]

因此,使用类似以下内容的东西:

use strict;
use warnings;
use utf8;
use Getopt::Long qw(Getoptions);

my @foos;
my @dates;

# INPUT
Getoptions(
    'foo|f:s'                                       => \@foos,'date|d:s'                                      => \@dates,# 'help|h'   => \&help,) or die "Invalid options passed to $0\n"; 

我希望能够以类似以下方式调用脚本:

perl script.pl --foo "Go with 1" --foo "Go with 2" --date "date1" --date "date2"

然后可以执行以下操作:

foreach my $i (0..scalar(@foos)){
  print $foos[$i] . " " . $dates[$i] . "\n";
}

获取

Go with 1 date1
Go with 2 date2

我为什么要这样做 ?:我为一个函数循环了不确定数量foos。在另一个函数中,我想再次遍历foo,并打印与之关联的日期如果存在

我要避免的事情:必须为foos的每个元素创建一个标志,如下所示:

Getoptions(
    'foo|f:s'                                               => \@foos,'date-foo-1|df1:s'                                      => \$dates_foo_1,'date-foo-2|df2:s'                                      => \$dates_foo_2,) or die "Invalid options passed to $0\n"; 

我认为我可以做的是将可选标志与另一个标志相关联,但是我找不到任何相关的东西。

解决方法

您的代码已经可以满足您的要求。

use strict;
use warnings;
use utf8; # This is unnecessart
use Getopt::Long qw(GetOptions);

my @foos;
my @dates;

# INPUT
GetOptions(
    'foo|f:s'  => \@foos,'date|d:s' => \@dates,# 'help|h'   => \&help,) or die "Invalid options passed to $0\n";

foreach my $i (0 .. scalar(@foos)){
  print $foos[$i] . " " . $dates[$i] . "\n";
}

输出为:

Go with 1 date1
Go with 2 date2
Use of uninitialized value in concatenation (.) or string at opts.pl line 17.
Use of uninitialized value in concatenation (.) or string at opts.pl line 17.

显示警告,因为您的数组遍历代码存在错误。您不想走0 .. scalar @foos,因为scalar @foos给出2,而@foos中的最高索引是1。

您可以使用scalar @foos代替$#foos来获得@foos中的最高索引。

foreach my $i (0 .. $#foos){
  print $foos[$i] . " " . $dates[$i] . "\n";
}

这也值得指出

print $foos[$i] . " " . $dates[$i] . "\n";

可以更简单地写为:

print "$foos[$i] $dates[$i]\n";

更新:在需要两个长度相同的列表的情况下,您可能还会查看Options with hash values

的文档