use strict; use warnings; my @lines = ( "t13:45\n", "D13:45\n", "S13:45 Unicorn\n", "D13:45\n", "S13:45\n", "T13:45\n", "t13:45\n", "D13:45\n", "T13:46\n", "t13:45\n", "D13:45\n", "S13:45\n","D13:45\n", "S13:45 UNICORN\n", "T13:45\n", "t13:45\n", "D13:45\n", "T13:46\n", ); use constant GOOD_LINE => qr{ \A [tTJSD] }xms; use constant END_SECTION => qr{ \A T }xms; my $value = "uNiCoRn"; my @section; LINE: while (my $line = shift @lines) { die "bad line '$line'" unless $line =~ GOOD_LINE; push @section, $line; next LINE unless $line =~ END_SECTION; if (grep m{ (?i) \Q$value\E }xms, @section) { print for @section; print "\n"; } @section = (); } __END__ t13:45 D13:45 S13:45 Unicorn D13:45 S13:45 T13:45 t13:45 D13:45 S13:45 D13:45 S13:45 UNICORN T13:45