Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


foreach $hostname (@hostnameUniqueSorted){
    $ipaddr = inet_ntoa((gethostbyname($hostname))[4]);
    if(chomp($ipaddr) =~ '^$') $ipaddr == "ip not avail";   <-- doesn't work

If the host doesn't return an IP address, it would break and show:

Usage: Socket::inet_ntoa(ip_address_sv) at ./abc line 24.

How do I catch it and assign maybe 'ip not avail' for the $ipaddr?

I added the last line but it doesn't work.

share|improve this question
up vote 1 down vote accepted

You should be checking the return value of gethostbyname - it returns an empty list if the host is not found, and inet_ntoa can't deal with that.

Try something like the following:

foreach my $hostname (@hostnameUniqueSorted) {
    my @host = gethostbyname($hostname);
    if (scalar(@host) == 0) {
        $ipaddr = "not found";
    } else {
        $ipaddr = inet_ntoa($host[4]);
    print $hostname, " => ", $ipaddr, "\n";

Note that your syntax is incorrect, {} are necessary after the if condition. And I don't believe chomp returns anything, so that test invalid. (And == is for comparison only, not assignment.)

share|improve this answer
Thanks, it works exactly like i want it to. – user11496 Jan 4 '12 at 10:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.