... my $previous_line; while (my $current_line = ) { if ( $current_line =~ /^PLACED/ && $previous_line =~ /^HERE IS THE DATA$/ ) { print $current_line; } $previous_line = $current_line; } #### ... my $seen_here_is_the_data; while (my $line = ) { $seen_here_is_the_data = 1 if $line =~ /^HERE IS THE DATA$/; if ( $seen_here_is_the_data && $previous_line =~ /^HERE IS THE DATA$/ ) { print $line; } }