2016-06-30 56 views
1

我在解析命令行參數時遇到了我的perl腳本問題。主要的是,我希望perl能夠解析(em/en)-dash之前的參數以及hypen。 請考慮下面的命令執行:Perl - 在命令行參數中輸入en/em破折號

my_spript.pl -firstParam someValue –secondParam someValue2 

正如你所看到的,firstParam加上前綴連字符並沒有用Perl解析它沒有問題,但secondParam的前綴是短破折號,不幸的Perl都不能認呢作爲論據。如果您使用Getopt::Long

GetOptions(
    "firstParam" => \$firstParam, 
    "secondParam" => \$secondParam 
) 
+0

你使用什麼模塊? [:: Getopt的龍(http://p3rl.org/Getopt::Long)? – choroba

+0

@choroba,是的。我確實使用Getopt :: Long – dejvid

+0

所有應有的尊重,這是一個瘋狂的要求。 – tripleee

回答

3

,可以預處理的參數它們給GetOptions前: 我使用GetOptions()來解析參數

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

use Getopt::Long; 

s/^\xe2\x80\x93/-/ for @ARGV; 

GetOptions('firstParam:s' => \ my $first_param, 
      'secondParam:s' => \ my $second_param); 
print "$first_param, $second_param\n"; 

這可能是更清潔,首先解碼論據,雖然:

use Encode; 

$_ = decode('UTF-8', $_), s/^\N{U+2013}/-/ for @ARGV; 

在不同的區域設置工作,使用Encode::Locale

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

use Encode::Locale; 
use Encode; 
use Getopt::Long; 

$_ = decode(locale => $_), s/^\N{U+2013}/-/ for @ARGV; 

GetOptions('firstParam:s' => \ my $first_param, 
      'secondParam:s' => \ my $second_param); 
print "$first_param, $second_param\n"; 
+0

它在OS-X上很好,但在Windows上似乎不起作用。 (perl版本:5.14.2)。你有什麼想法可能是錯的? – dejvid

+1

在Windows上,終端編碼可能不是UTF-8。指定正確的編碼。 – choroba

+0

@dejvid:檢查更新。 – choroba