my $previous = ''; foreach my $line (@arrayfile) { if ($line =~ m/WhateverIWantToMatch/) { print "$previous\n" if ($previous); } $previous = $line; #### This line now becomes the previous line for the next array element seeing as ALL lines in the file will be processed }