in reply to Re: Net::DNS answer count
in thread Net::DNS answer count
So I got the code to work by doing the following:
Is there a better way to do this with the code originally posted?
my $query = $resolver->query($target_ip, 'PTR'); my @answer = $query->answer; print "Total # of Hostnames found: ", scalar(@answer), "\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Net::DNS answer count
by kcott (Archbishop) on Apr 10, 2023 at 06:37 UTC | |
"Is there a better way to do this with the code originally posted?" In essence, no. You want the value of @answer in the loop just after reporting the count, so it makes sense to assign 'my @answer =' once and then reuse the value. If you're asking specifically about the print statement, what you have is fine. There are multiple ways of doing this and, for the most part, it would come down to personal style more than anything else. I tend to favour '0+@array' over 'scalar(@array)'; but that's just me. Here's a handful of different ways you could do this:
[See "discussion of @{[...]}" (from a few days ago) if you're unfamiliar with that construct.] In the main, your code is fine. There's one subtlety of which few are aware (or fully understand) — don't feel too bad about this slip-up by yourself. :-) The loop variable in a for loop is lexically scoped to that loop. Other references to variables of the same name outside the loop are different variables. Consider these (and note that I had to turn off strict for demonstration purposes):
With strict enabled, the $i outside the loop is problematic:
There is an anomaly with this. I consider it to be a bug in Perl and probably the cause of much confusion. If you don't declare the loop variable with my, strict complains:
unless you've previously declared a different variable with the same name with my in an outer scope:
Declaration after the loop still raises an error with the loop variable:
Here's a very quick review of the remainder; bear in mind that much of this comes down to style as opposed to corrections:
— Ken | [reply] [d/l] [select] |
by g_speran (Scribe) on Apr 10, 2023 at 13:21 UTC | |
| [reply] |