我希望在perl腳本中寫下接收和選項,值列表以雙短劃線( - )結尾。 例如:Perl:使用GetOpt時,是否可以防止選項識別在雙破折號( - )後停止?
% perl_script -letters a b c -- -words he she we --
作爲運行此命令行的結果,兩個陣列將被創建: 字母= [A B C]。 words = [he she we];
使用GetOption不支持這一點,b.c使用雙短劃線後,選項識別停止。
我希望在perl腳本中寫下接收和選項,值列表以雙短劃線( - )結尾。 例如:Perl:使用GetOpt時,是否可以防止選項識別在雙破折號( - )後停止?
% perl_script -letters a b c -- -words he she we --
作爲運行此命令行的結果,兩個陣列將被創建: 字母= [A B C]。 words = [he she we];
使用GetOption不支持這一點,b.c使用雙短劃線後,選項識別停止。
如何
-letters "a b c" -words "he she we"
?
你有一些具體的理由使用這樣一個混亂的分隔符? --
對大多數腳本用戶來說都有一個已知的含義,這不是它。
如果你需要閱讀帶有列表的選項,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
您可以處理你的論點多遍,如果你想要的。看看pass_through選項。這是我在ack中所做的,因爲有些選項會影響其他選項,所以我必須先處理--type選項,然後處理剩下的選項。
做了這些建議的任何工作嗎?是不是很正確? – 2011-03-02 13:23:23