#!/usr/bin/perl use strict; use warnings; my %header = (); my $within_body = ''; my @search_strings = qw(stringa stringb stringc); while () { chomp; if ($_ =~ /^\*{3} (.+?)$/) { $within_body = $1; } else { foreach my $search_strings (@search_strings) { if (/$search_strings/) { push (@{$header{$within_body}}, $search_strings); } } } } foreach my $section (sort keys %header) { print "Found the following strings within body *** $section\n"; print join("\n", @{$header{$section}}); print "\n"; } __DATA__ *** 3993.2399 stringa stringb stringc *** 3993.23384j stringc junk data junk data *** 3993.23993k stringa stringb junk data junk data #### if ( @{$header{$section}} = /stringa/gm ) { print "matched on stringa\n"; } if ( @{$header{$section}} = /stringb/gm ) { print "regex on string b\n"; } if ( @{$header{$section}} = /stringc/gm ) { print "C match\n"; } #### Found the following strings within body *** 3993.23384j stringc Found the following strings within body *** 3993.2399 stringa stringb stringc Found the following strings within body *** 3993.23993k stringa stringb #### Found the following strings within body *** 3993.23384j C match Found the following strings within body *** 3993.2399 matched on stringa regex on string b C match Found the following strings within body *** 3993.23993k matched on stringa regex on string b