2015-06-03 104 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(..)