如何将结果从shell脚本返回到perl?

how to return results from shell script to perl?

我尝试从perl的shell脚本中获得rtt结果(例如149.982 / 150.125 / 150.280 / 0.265 ms),
现在ping.sh可以从shell脚本中检索rtt结果了,但是如何在perl中返回结果以及如何从shell脚本中获得返回结果呢?

call.pl

1
2
3
4
5
6
7
8
my $answer= system (".  /home/george/ping.sh;getrtt  8.8.8.8");
if($answer == 0)
{
    exit($answer >> 8);
    my $results =  ##how to get the rtt results from ping.sh ???


 }

ping.sh

1
2
3
4
5
6
7
8
9
getrtt()
{
   if  ping $ip -c 5 -t 5 | grep -oP '[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+ ms'
   then
      echo ##how to retrun the results (ping $ip -c 5 -t 5 | grep -oP '[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+\\/[+-]?([0-9]*[.])?[0-9]+ ms')???
   else
      echo '1'
 fi
 }


在shell函数中:

  • 您可以使用$()语法在变量中获取ping的结果
  • 您可以回显结果
  • 在perl程序中:
    您可以打开管道|并读出shell stdout

    文件ping.sh:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    getrtt()
    {
       ip=$1;
       if result=$(ping $ip -c 5 -t 5 | grep -P 'ms$')
       then
          echo $result
       else
          echo '1'
     fi
     }

    文件graboutput.pl:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #!/usr/bin/perl

    local *EXEC; open EXEC,'. ./ping.sh && getrtt 8.8.8.8|' or die $!;
    while (<EXEC>) {
     # do something with the result
     print;
    }
    close EXEC;

    exit $?;

    1; # $Source: /my/perlscritps/graboutput.pl$

    注意:我的linux盒上的ping格式不相同
    即:5 packets transmitted, 0 received, +5 errors, 100% packet loss, time 4005ms
    所以我更改了带有ping.sh

    的grep的-oP选项