There are a number of ways to implement this code.
One is shown below.
Basically, keep track of the last hostname found. When you find a valid ip, and that ip is the one that you are looking for, then that goes with the most previous hostname.
#!usr/bin/perl
use warnings;
use strict;
my $file =<<END;
object-group network HOSTNAME_1ST
network-object host 10.1.1.1
object-group network HOSTNAME_2nd
network-object host 10.3.1.1
object-group service WEB_TCP tcp
port-object eq 80
END
my $hostname;
open my $fh, '<', \$file or die "unable to open read file $!";
while (my $line = <$fh>)
{
if (my ($name) = $line =~ /^object-group network (\w+)/)
{
$hostname = $name; # "last seen hostname"
}
my ($ip) = $line =~ /(\d+\.\d+\.\d+\.\d+)/;
if (defined ($ip) and $ip eq '10.3.1.1')
{
print "ip $ip goes with host name $hostname\n";
}
}
__END__
ip 10.3.1.1 goes with host name HOSTNAME_2nd