2011-12-07 12 views
1

我的一個同事寫了一個Perl腳本,要求用戶輸入的Windows域/用戶名,這當然是我們進入下面的格式domainname\username。 Getopt:Long模塊然後將其轉換爲一個字符串,它會刪除'\'字符並使字符串不正確。當然,我們可以要求我們所有的用戶輸入他們的域名/用戶組合,作爲domainname\\username,但我真的不想有罪「修復用戶,而不是程序」。我們也使用我們爲此製作的模塊,因爲它訪問ColdFusion,所以我會打電話給OurCompany::ColdFusionAPI製作的Perl的Getopt ::長期保持反斜線()在字符串

我們的代碼看起來是這樣的:

#!/usr/bin/perl 

use common::sense; 
use Getopt::Long; 

use OurCompany::ColdFusionAPI; 

my ($server_ip, $username, $password, $need_help); 

GetOptions (
    "ip|server-address=s" => \$server_ip, 
    "user-name=s"   => \$username, 
    "password=s"   => \$password, 
    "h|help"    => \$need_help, 
); 
$username ||= shift; 
$password ||= shift; 
$server_ip ||= shift; 

if (!$server_ip or $need_help){ 
    print_help(); 
    exit 0; 
} 

my $print_hash = sub { my $a = shift; say "$_\t=> $a->{$_}" foreach keys %$a; }; 

... 

如果我添加行say $username然後它只是給沒有「\」的字符串。我怎樣才能讓perl保持'\'?在bash中沿着read -r的一些東西。

+0

什麼' '\''你在說什麼? – Axeman

+0

爲什麼首先使用反斜槓?正斜槓更容易在鍵盤上觸及。 – runrig

回答

11

殼牌這樣做,沒有getopt的::長。您需要跳過\以使您的shell將其解釋爲文字反斜槓,而不是試圖轉義某些內容。

+0

+1這是正確的,併爲8秒早於我的;) – Konerak

+0

''d \ u''和' 「d \ U」'都正常工作太 –

9

你確定這是由於對getopt ::龍?很有可能你的shell已經在解析你正在輸入的內容,並且弄亂了反斜槓。

爲什麼不問域和用戶名seperately?這會稍微優雅地解決問題。