带参数的perl函数调用

时间:2015-06-03 14:52:29

标签: perl subroutine

我编写了一个在远程机器上执行命令的函数。

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 个答案:

答案 0 :(得分: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(..)

时会出现错误

答案 1 :(得分:1)

如果未设置空字符串,则为它们分配:

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

此外,正如choroba所指出,您需要在execute来电中使用双引号,而不是单引号。