0

I want to modify a Perl script to save the result to text file output.txt and open the results output.txt when task is done

I have tried used "use strict; use warnings;" and other methods but I keep getting an errors' The Last error was "Couldn't open 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; 
  }

}

after running cmd as Admin , as you can see the report.txt file shows empty I expect to see the out put of the Response

I also want perl to open the report.txt ( without going to windows explorer and opening it manually by the user ) I want it automatically open when its done but I wasn't able to achieve that.

Thanks!

Dave Cross
  • 68,119
  • 3
  • 51
  • 97
jason
  • 1
  • I've fixed the indentation of your code. You're welcome, of course, but please consider doing it yourself in the future. Good indentation is a powerful tool for helping people understand your code. If you want people to read and understand your code, then it's a good idea to get the indentation right. – Dave Cross May 28 '19 at 09:04

2 Answers2

1

Seems you're always overwriting your report file.

Your open is inside the foreach loop. The loop is done 4 times. You will only receive the output of the last run as the first 3 file creations will be overwritten by the last one.

You should put the open and close outside the loop.

If you only need the first result, you can leave, the loop by putting a last statement at the end of the "then-part" of your if.

Skeeve
  • 7,188
  • 2
  • 16
  • 26
0

Try changing open(my $fh, '>', $filename) to open(my $fh, '>>', $filename) (two arrows instead of one. This will add each new entry instead of delete the last one.

Here are some answers on opening Windows files with Perl:
How to run an executable file using Perl on Windows XP?

Bman70
  • 743
  • 5
  • 11
  • What's the advantage of opening and closing the same file each run through the loop over opening and closing outside the loop? – Skeeve May 27 '19 at 06:57