Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PERL Net::DNS output to file

Tags:

perl

dns

Completely new to Perl (in the process of learning) and need some help. Here is some code that I found which prints results to the screen great, but I want it printed to a file. How can I do this? When I open a file and send output to it, I get garbage data.

Here is the code:

use Net::DNS;
my $res  = Net::DNS::Resolver->new;
$res->nameservers("ns.example.com");

my @zone = $res->axfr("example.com");

foreach $rr (@zone) {
$rr->print;
}

When I add:

open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
.....
$rr -> $fh; #I get garbage.
like image 220
DaveS Avatar asked Mar 14 '23 13:03

DaveS


2 Answers

Your @zone array contains a list of Net::DNS::RR objects, whose print method stringifies the object and prints it to the currently selected file handle

To print the same thing to a different file handle you will have to stringify the object yourself

This should work

open my $fh, '>', $filename or die "Could not open file '$filename': $!";

print $fh $_->string, "\n" for @zone;
like image 54
Borodin Avatar answered Apr 06 '23 06:04

Borodin


When you're learning a new language, making random changes to code in the hope that they will do what you want is not a good idea. A far better approach is to read the documentation for the libraries and functions that you are using.

The original code uses $rr->print. The documentation for Net::DNS::Resolver says:

print

$resolver->print;

Prints the resolver state on the standard output.

The print() method there is named after the standard Perl print function which we can use to print data to any filehandle. There's a Net::DNS::Resolver method called string which is documented like this:

string

print $resolver->string;

Returns a string representation of the resolver state.

So it looks like $rr->print is equivalent to print $rr->string. And it's simple enough to change that to print to your new filehandle.

print $fh $rr->string;

p.s. And, by the way, it's "Perl", not "PERL".

like image 21
Dave Cross Avatar answered Apr 06 '23 06:04

Dave Cross