title: How can I write output to a new external file with Perl?
body: <p>Maybe I am searching with the wrong keywords or this is a very basic question but I cannot find the answer to my question. I am having trouble writing the result of my whois command to a new external file.</p>
  
  <p>My code is below. It takes <code>$readfilename</code>, which is a file name which has a list of IPs, and <code>$writefilename</code>, which is the destination file for output. Both are user-specified. For my tests, <code>$readfilename</code> contains three IP addresses on three separate lines so there should be three separate whois results in the user specified output file.</p>
  
  <pre><code>if ($readfilename) {
      open (my $inputfile, "&lt;", $readfilename) || die "\n   Cannot open the specified file.     Please double check your file name and path.\n\n";
      open (my $outputfile, "&gt;", $writefilename) || die "\n   Could not create write file.\n\n";
      while (&lt;$inputfile&gt;) {
          my $iplookupresult = `whois $_ &gt; $writefilename`;
          print $outputfile $iplookupresult;
      }
      close $outputfile;
      close $inputfile;
  }
  </code></pre>
  
  <p>I can execute this script and end up with a new external file, but over half of the file has binary garbage data (running on CentOS) and only one (or a portion of one) of the whois lookups is readable.</p>
  
  <p>I have no idea how half of my file is ending up binary... but my approach must be incorrect. Is there a better way to achieve the same result? </p>