2015-06-03 106 views
0

我寫了一個函數來在遠程機器上執行一個命令。帶參數的perl函數調用

Command : iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 $okey $ikey 

$okey $ikey值作爲參數傳遞。

現在,有時我想執行命令WITHOUT $ okey和$ ikey值。

Command : iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 

現在我的問題是,我如何通過$ okey和$ ikey值作爲可選參數。如果$ okey和$ ikey值不通過,那麼必須執行下面的命令。

iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 

如果傳遞$ okey和$ ikey值,則必須執行以下命令。

iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 $okey $ikey 

功能:

sub gre_testing { 
     my ($self,$okey,$ikey) = @_; 
     $self->execute('iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 $okey $ikey'); 
     return 1; 
} 

函數調用:

gre_testing(1000,1000); 
+2

單引號不插入變量時,你會得到一個錯誤。使用雙引號。 – choroba

+0

'我($ self,$ okey,$ ikey)=(@_,(「」)x 3 - @ _);' –

+1

@Сухой27這有點讓人困惑。至少對我來說:| –

回答

1

分配他們的空字符串,如果他們不設置:

unless (defined $okey && defined $ikey) 
{ 
    $okey = $ikey = ""; 
} 

此外,作爲choroba尖出去,你需要你您的execute調用中不包含單引號。

4

如果你想他們是可選的,你需要在你的gre_testing子程序實際上寫的是支持:

sub gre_testing { 
    my ($self, $okey, $ikey) = @_; 

    # if these arguments are not passed 
    # use the empty string so no value is interpolated below 
    $okey //= ''; 
    $ikey //= ''; 

    $self->execute(
     "iptunnel add obs mode gre remote x.x.x.x local X.X.X.X ttl 225 $okey $ikey" 
    ); 
    return 1; 
} 

的另一個問題是要傳遞到執行字符串是引用單引號,所以沒有你的變量將被內插。使用雙引號。

現在在你不想$okey$ikey你輕輕的說了情況:

$self->gre_testing(); 

我注意到你在上面定義$self,但沒有調用您的方法的對象。我想你想這樣做,否則當你嘗試$self->execute(..)