my($valid_ip, $valid_external); foreach my $check (@IPs) { # clean it up $check =~ s/^\s*(.*?)\s*$/\1/; # skip if not a valid IP next unless is_ip($check); # overwrite with the last IP we saw that's valid $valid_ip = $check; # skip unless it's an external IP next if (not is_public_ip($check)) or (is_loopback_ip($check)) or ($check eq "41.79.21.90"); # overwrite with the last valid IP that is external $valid_external = $check; } # choose last external IP if we found one, else last valid IP my $ip = $valid_external // $valid_ip;