tags:

views:

435

answers:

1

I wrote a quick Perl script to query the local DNS servers for an IP address, and I have a variable that needs to be declared within the scope of the loop, but it doesn't seem to be in scope outside of the loop. The compiler is returning the errors

Global Symbol "$ipAddr" requires explicit package name

Here's the code

my $resolver = Net::DNS::Resolver->new;

my $dnsQuery = $resolver->search($hostIP[0]->getFirstChild->getData);

if ($dnsQuery) {
    foreach my $rr ($dnsQuery->answer) {
        next unless $rr->type eq "A";
        my $ipAddr = ip2dec($rr->address);
    }
}

print( "::".$ipAddr );

How would it be possible to declare a variable in this manner that would be accessible from outside of the loop?

+12  A: 

Put the my $ipAddr declaration outside the loop:

my $dnsQuery = $resolver->search($hostIP[0]->getFirstChild->getData);
my $ipAddr;
if ($dnsQuery) {
        foreach my $rr ($dnsQuery->answer) {
                next unless $rr->type eq "A";
                $ipAddr = ip2dec($rr->address);
        }
}
print("::".$ipAddr);
mobrule
Thanks, I figured that out shortly after I posted, but got all kinds of errors when I tried it so I was wondering if that was still valid.
if you're not in "use strict" you can also just take off the "my"
arolson101
Not using "use strict" is like drive 100 MPH without a seat belt -- a very bad idea unless you are absolutely sure you know what you are doing and if you think you know what you are doing, you're probably wrong.
mikegrb