0

抑制 Perl 代码的系统输出。

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

如果 lists.hosts 文件中有一个域无法解析,屏幕输出将包含:“ping: cannot resolve XXX.com: Unknown host”

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);
4

1 回答 1

1

您调用ping需要捕获标准错误:

ping -c 1 $host 2>&1

此外,您没有检查您的退货,open您应该始终这样做。最后,您应该在顶部使用use warnings;和。use strict;

于 2014-06-10T18:51:43.677 回答