my $previous = ""; while(defined(my $line = <>)) { chomp $line; ($previous . $line) =~ m/$pattern/ and say $line; $previous = $line; }