my $host; while (<$fh>) { if (/^hostname/) { $host = new_host( $_ ); next; }; if ($host) { add_to_host( $host, $_ ); }; }; sub new_host { ... }; # return id of new host section sub add_to_host { ... }; # do whatever is needed