perl:函数调用

时间:2014-07-04 21:43:20

标签: perl function

以下脚本用于ssh到路由器,从文件abc.txt读取信息并执行命令。该脚本按预期工作。

use strict;
use warnings;
use autodie;
use feature qw/say/;
use Net::SSH::Expect;

print "\n[INFO] script Execution Started\n";


my $ssh = Net::SSH::Expect->new(
  host     => "ip addr",
  password => ' user ',
  user     => 'pwd',
  raw_pty  => 1,
);

my $login_output = $ssh->login();


$ssh->exec("enter command 1");
$ssh->exec("enter command 2");
open my $pr, '<', 'abc.txt';
while (my $config = <$pr>) {
chomp $config;
my $conf =  $ssh->exec("$config");
print("$conf");

}

现在我将上面代码的一部分转换为函数。这就是我尝试过的。 所以我要做的就是进行函数调用来打开文件。 mysub($ssh,"abc.txt"); 这样我就可以在我的程序中重用这段代码来打开多个配置文件。

use strict;
use warnings;
use autodie;
use feature qw/say/;
use Net::SSH::Expect;

print "\n[INFO] script Execution Started\n";


my $ssh = Net::SSH::Expect->new(
  host     => "ip addr",
  password => 'user',
  user     => 'pwd',
  raw_pty  => 1,
);


sub mysub {

my ($ssh,$filename) = @_;
$ssh->exec("command 1");
$ssh->exec("command 2");
open my $pr, '<', $filename;
while (my $config = <$pr>)
{
chomp $config;
my $conf =  $ssh->exec("$config");
print("$conf");

}

mysub($ssh,"abc.txt");

}

函数调用部分不起作用,不会抛出任何错误。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:5)

如果使用适当的缩进,您的错误就会变得明显:

sub mysub {
    my ($ssh,$filename) = @_;
    $ssh->exec("command 1");
    $ssh->exec("command 2");
    open my $pr, '<', $filename;
    while (my $config = <$pr>)
    {
        chomp $config;
        my $conf =  $ssh->exec("$config");
        print("$conf");

    }
    mysub($ssh,"abc.txt");   # this should be outside
}

您必须将函数调用放在子例程之外。