Perl使用ping抑制反引号输出

时间:2014-06-10 18:48:03

标签: perl system output suppress

从Perl代码中抑制系统输出。

此代码在功能上运行良好,直到我遇到无法解析的主机名并希望抑制无法解析的域的输出。

如果在lists.hosts文件中存在无法解析的域,则屏幕输出将包含:" ping:无法解析XXX.com:未知主机"

my $ip;

open(HOSTLIST, "lists.hosts");    # Load domains
@hosts = <HOSTLIST>;
chomp($host);

foreach $host (@hosts) {

  $results = `ping -c 1 $host`;

  $record++;

  my $pos = index($results, $find);

  if (($results =~ /ttl=/) || ($results =~ /data bytes/)) {
    #$count++;
    chomp($host);
    if (($results =~ /(?<=bytes from)(.*)(?=:)/) != 0) {
      ($ip) = ($results =~ /(?<=bytes from)(.*)(?=:)/);
    }
    elsif (($results =~ /(?<=\()(.*)(?=\))/) != 0) {
      ($ip) = ($results =~ /(?<=\()(.*)(?=\))/);
    }

    print "Record: $record Host: $host IP:$ip Status: Passed";
    print "\n";

    #print ("*** Record# $record: Ping Test Succeeded for Server: $host ***\n");
    #print ("$results\n");
  }
  else {
    $count++;
    chomp($host);

    #print ("*** Record# $record: Ping Test Failed for Server: $host ***\n");
    print "Record: $record Host: $host Status: Failed\n";

    #print ("$results\n");
  }
}

close(HOSTLIST);

exit($errorcode);

1 个答案:

答案 0 :(得分:1)

您对ping的调用需要捕获stderr:

ping -c 1 $host 2>&1

此外,您不会检查open的返回,您应该始终这样做。最后,您应该在顶部使用use warnings;use strict;