How can I access the variable outside of the loop when I set it inside the loop?

I wrote a quick Perl script to query local DNS servers for an IP address, and I have a variable that needs to be declared within a loop, but it doesn't appear to be scoped outside the loop. The compiler returns 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 can you declare a variable in such a way that it will be accessible from outside the loop?

+2


source to share


1 answer


Place the declaration my $ipAddr

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);

      

+14


source







All Articles