【问题标题】:How Can I output the response to text file and open the text file when done如何将响应输出到文本文件并在完成后打开文本文件
【发布时间】:2019-10-12 07:27:52
【问题描述】:

我想修改一个 Perl 脚本以将结果保存到文本文件 output.txt 并在任务完成后打开结果 output.txt

我试过用“use strict; 使用警告;”和其他方法,但我不断收到错误“最后一个错误是“无法打开 output.txt”

#!/usr/bin/perl

use HTTP::Request;
use LWP::UserAgent;

system('cls');
system "color c";
print"\n";
print" |||||||||||||||||Robots scanner|||||||||||||||||||||";
print "\n";

print " Scan Your site Site\n\n Example: www.test.com \n\n-> ";


$site=<STDIN>;
chomp $site;

if($site !~ /http:\/\//) { $site = "http://$site/"; };

print "\n";

@path = ('robotx.txt','robots.txt','robot.txt','search',);


foreach $robots(@path){

  $url = $site.$robots;
  $req = HTTP::Request->new(GET=>$url);
  $useragent = LWP::UserAgent->new();

  $response = $useragent->request($req);
  my $filename = 'report.txt';
  open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
  if ($response->is_success){

    print  ">>>>>>Robots Found !!!>>>: $url\n";
    print $fh "out put has been generated by perl\n"; # THIS DOESN'T WORK THE report.txt is empty 
    print "done\n";

  }else{
    print "NotFound : $robots\n";
    print "done\n";
    # I want to open the file from windows explorer automatically here when its done 
    close $fh; 
  }

}

以 Admin 身份运行 cmd 后,您可以看到 report.txt 文件显示为空 我希望看到响应的输出

我还希望 perl 打开 report.txt(无需转到 Windows 资源管理器并由用户手动打开)我希望它在完成后自动打开,但我无法实现。

谢谢!

【问题讨论】:

  • 我已经修复了代码的缩进。当然,不客气,但请考虑以后自己做。良好的缩进是帮助人们理解你的代码的强大工具。如果您希望人们阅读和理解您的代码,那么最好使用正确的缩进。

标签: perl file-io


【解决方案1】:

您似乎总是在覆盖您的报告文件。

您的 open 在 foreach 循环内。循环完成 4 次。您只会收到最后一次运行的输出,因为前 3 个文件创建将被最后一个文件覆盖。

你应该把打开和关闭放在循环之外。

如果您只需要第一个结果,您可以通过在if 的“then-part”末尾添加last 语句来退出循环。

【讨论】:

    【解决方案2】:

    尝试将open(my $fh, '&gt;', $filename) 更改为open(my $fh, '&gt;&gt;', $filename)(两个箭头而不是一个。这将添加每个新条目而不是删除最后一个。

    以下是一些关于使用 Perl 打开 Windows 文件的答案:
    How to run an executable file using Perl on Windows XP?

    【讨论】:

    • 在循环中打开和关闭同一个文件比在循环外打开和关闭有什么好处?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多