#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @result; my $file = '/path/to/file'; open my $fh,"<",$file or die $!; local $/ = "\n...\n"; while(my $entry = <$fh>){ my $bool = 0; my @lines = split /\n/,$entry; my @aacc = grep{/^(?:AA|CC)/}@lines; my @temp = grep{/^(?:BB|DD|EE)/}@lines; if(grep{/Mercedes/}@aacc){ push @result,\@temp; } } close $fh; print Dumper(\@result);