【问题标题】:Perl suppress backtick output with pingPerl 使用 ping 抑制反引号输出
【发布时间】:2014-06-10 18:48:03
【问题描述】:

抑制 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);

【问题讨论】:

  • 始终 use strictuse warnings 在您编写的每个 Perl 程序的开头。这尤其适用于您寻求代码帮助时。您还应该正确缩进代码以使其可读。在这种情况下,我已经为您完成了,但您应该自己完成,因为它可以帮助您查看代码的流程并更容易发现任何错误

标签: perl system output suppress


【解决方案1】:

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

ping -c 1 $host 2>&1

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

【讨论】:

  • 我确实尝试将 stderr 发送到 null 并且仍然发出 ping 错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 2023-03-23
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
相关资源
最近更新 更多