2011-02-15 41 views
1

我希望在perl脚本中写下接收和选项,值列表以双短划线( - )结尾。 例如:Perl:使用GetOpt时,是否可以防止选项识别在双破折号( - )后停止?

% perl_script -letters a b c -- -words he she we -- 

作为运行此命令行的结果,两个阵列将被创建: 字母= [A B C]。 words = [he she we];

使用GetOption不支持这一点,b.c使用双短划线后,选项识别停止。

+0

做了这些建议的任何工作吗?是不是很正确? – 2011-03-02 13:23:23

回答

3

如何

-letters "a b c" -words "he she we" 

5

你有一些具体的理由使用这样一个混乱的分隔符? --对大多数脚本用户来说都有一个已知的含义,这不是它。

如果你需要阅读带有列表的选项,Getopt::Long有处理输入数组的方法,也许这样的东西可以帮助你;查看"Options with multiple values"。这个模块是标准的发行版,所以你甚至不需要安装任何东西。我将它用于需要多于一个(也许是两个)输入的任何脚本,并且如果有任何输入是可选的。请参阅here甚至更​​多here

下面是一个简单的例子,如果你有灵活地改变你的输入语法,这可以让你您所请求的功能:

#!/usr/bin/env perl 
# file: test.pl 

use strict; 
use warnings; 

use Getopt::Long; 

my @letters; 
my @words; 

GetOptions(
    "letters=s{,}" => \@letters, 
    "words=s{,}" => \@words 
); 

print "Letters: " . join(", ", @letters) . "\n"; 
print "Words: " . join(", ", @words) . "\n"; 

给出:

$ ./test.pl --letters a b c --words he she we 
Letters: a, b, c 
Words: he, she, we 

虽然我永远不会鼓励写一个自己的解析器,我不明白为什么有人会选择你的表单,所以我会在假设你不能控制这个表单的情况下运行并且需要解决它。如果是这种情况(否则,请考虑使用更标准的语法并使用上面的示例),这里有一个简单的解析器,可以帮助您开始。

N.B.不写自己的原因是其他人都经过了充分的测试,并且有了一些额外的案例。你也知道你会怎么处理---title之间的事情吗?我认为,由于新的标题会结束前一个标题,因此您可能会介入一些内容,并将所有这些按顺序排列在“默认”键中。

#!/usr/bin/env perl 
# file: test_as_asked.pl 
# @ARGV = qw/default1 -letters a b c -- default2 -words he she we -- default3/; 

use strict; 
use warnings; 

my %opts; 
# catch options before a -title (into group called default) 
my $current_group = 'default'; 
foreach my $opt (@ARGV) { 
    if ($opt =~ /\-\-/) { 
    # catch options between a -- and next -title 
    $current_group = 'default'; 
    } elsif ($opt =~ /\-(.*)/) { 
    $current_group = $1; 
    } else { 
    push @{ $opts{$current_group} }, $opt; 
    } 
} 

foreach my $key (keys %opts) { 
    print "$key => " . join(", ", @{ $opts{$key} }) . "\n"; 
} 

给出:

$ ./test_as_asked.pl default1 -letters a b c -- default2 -words he she we -- default3 
letters => a, b, c 
default => default1, default2, default3 
words => he, she, we 
2

您可以处理你的论点多遍,如果你想要的。看看pass_through选项。这是我在ack中所做的,因为有些选项会影响其他选项,所以我必须先处理--type选项,然后处理剩下的选项。

相关问题