2012-04-02 49 views
-1

代碼:奇怪的getopt = s處理?

#!/usr/bin/env perl 
use strict; 
use warnings; 
use locale; 

my $prepinac_r = ''; 
my $array_name = ''; 

use Getopt::Long; 
Getopt::Long::Configure ("bundling"); 
my $result = GetOptions(
"r=s" => \$prepinac_r, 
"array-name=s" => \$array_name); 

print STDERR "r: $prepinac_r\n"; 
print STDERR "array_name: $array_name\n"; 

運行它:

script.pl --array-name=kokos -r=kure 

輸出:

r: =kure 
array_name: kokos 

我做錯了嗎?我錯過了什麼?爲什麼-r獲得「= kure」而不是「kure」?請幫助...

+0

Getopt :: Long :: Configure(「bundling_override」); – rluks 2012-04-07 07:42:35

回答

4

您正在混合簡短格式和長格式語法。簡寫形式的語法不會使用=,因爲這會縮短文本的長度。

"a|all"  => \$opt_all, 
"e|execute=s" => \$opt_execute, 

簡稱:

-aefoo 
-a -efoo 
-a -e foo 

朗形式:

--all --execute=foo 
--all --execute foo 

這裏是你可能熟悉的縮寫形式的一個例子:

perl -le'print "Hello World";' 
perl -l -e'print "Hello World";' 
perl -l -e 'print "Hello World";' 
+0

如果'-x = x'或'x = x'''-e = x = x'表示允許'='的簡寫形式,那麼將無法知道。 – ikegami 2012-04-04 07:38:44

1

學生先生,你應該使用雙重-兩個開關>>

script.pl --array-name=coconut --r=chicken 

...

r: chicken 
array_name: coconut 
+0

這會阻止他特別啓用的捆綁。 – ikegami 2012-04-04 07:39:45

+0

是的,我也會這樣做,但我對程序參數有嚴格的限制 – rluks 2012-04-07 07:41:52

0

我相信你所看到的行爲是因爲 「捆綁」 的。

Getopt::Long

Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options must be introduced with -- and bundles with - 

因此,如果您使用的是「捆綁式」,然後 -

--array-name=foo --r=bar # Works 
-afoo -rbar    # Also works 

--array-name=foo -r=bar # Does not. as you've already seen 

它也沒有意義的,使用綁定,除非你正在使用的選項,不需要參數,因此可以「捆綁」