开发者

How can I write output to a new external file with Perl?

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.

My code is below. It takes $readfilename, which is a file name which has a list of IPs, and $writefilename, which is the destination file for output. Both are user-specified. For my tests, $readfilename contains three IP addresses on three separate lines so there should be three separate whois results in the user specified output file.

if ($readfilename) {
    open (my $inputfile, "<", $readfilename) || die "\n   Cannot open the specified file.     Please double check your file name and path.\n\n";
    open (my $outputfile, ">", $writefilename) || die "\n   Could not create write file.\n\n";
    while (<$inputfile>) {
        my $iplookupresult = `whois $_ > $writefilename`;
        print $outputfile $iplookupresult;
    }
    close $outputfile;
    close $inputfile;
}

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.

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?


You're using shell redirection to redirect the output of whois to a file. But you've also opened the file for writing and are attempting to write data to the same file, giving you garbage. Just drop the shell redirection:

print $outputfile `whois $_`;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜