perl system函数返回值问题


在Perl脚本中,允许调用系统的命令来进行操作。这就是Perl灵活性的体现,作为一种系统命令的粘合语言,能给程序员带来许多的便利。这样,你就可以最大限度地利用别人的成果,用不着自己使劲造轮子了。

在Perl中,可以用system、exec、readpipe这三个命令来调用其他脚本、系统命令等。这三个命令的主要区别就是返回值。

1) 对于system这个函数来说,它会返回执行后的状态,比如说

    @args = (“command”, “arg1″, “arg2″);
    system(@args) == 0
    or die “system @args failed: $?”

当然,你也可以用类似于下面的语句来检查出错的原因:

    if ($? == -1) {
    print “failed to execute: $!\n”;
    }
    elsif ($? & 127) {
    printf “child died with signal %d, %s coredump\n”,
    ($? & 127),  ($? & 128) ? ‘with’ : ‘without’;
    }
    else {
    printf “child exited with value %d\n”, $? >> 8;
    }

2) 而对于exec这个函数来说,仅仅是执行一个系统的命令,一般情况下并没有返回值。exec只有在系统没有你要执行的命令的情况下,才会返回false值。

    exec (‘foo’)   or print STDERR “couldn’t exec foo: $!”;
    { exec (‘foo’) }; print STDERR “couldn’t exec foo: $!”;

3) 当我们需要保存系统命令运行的结果,以便分析并作进一步的处理时,就要用到readpipe这个函数了。例如:

    @result = readpipe( “ls -l /tmp” );
    print “@result”;

会产生如下的结果:

    drwxr-xr-x  2 root   root    4096 Mar 19 11:55 testdir

当然,你也可以把生成的结果放到一个文件里,以便写工作日志呀、发布报告呀。

    $inject_command = “./ConfigChecker.bat F:/nic/3502/ARRAY-4AD2E0573/etc “.$device_name;
    chdir “F:/TestTools/bin/”;
    @temp_result = readpipe($inject_command);
    open(result_file,”>result.txt”);
    print result_file @temp_result;
    close(result_file);

这样,你就把系统运行的结果扔到了系统命令所在目录下的result.txt文件里了。

这三个命令,有各自的特点,需要在使用时灵活选用,更详细的资料就得上PerlDoc上找了。

注解:
1;$result=system( '外部命令 ');
这个result只是返回命令是否成功,而不是外部命令的打印结果
2;

猜你喜欢

转载自blog.csdn.net/konglongaa/article/details/80452059