DaveS
DaveS

Reputation: 53

PERL Net::DNS output to file

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.

Upvotes: 4

Views: 169

Answers (2)

Borodin
Borodin

Reputation: 126722

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;

Upvotes: 4

Dave Cross
Dave Cross

Reputation: 69244

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".

Upvotes: 3

Related Questions