#! perl use strict; use warnings; my @lines = ("First line\n", "Second line\n", "Third line\n", "Fourth line\n", "Fifth line\n",); my @keywords = qw(Second Fourth); my @matches; for (my $i = 0; $i < $#lines; ++$i) { my ($first_word) = $lines[$i] =~ /^\s*(\w+)\b/; for (@keywords) { if ($_ eq $first_word) # Look for a keyword { chomp(my $line1 = $lines[$i ]); # *see below chomp(my $line2 = $lines[$i + 1]); # *see below push @matches, $line1 . $line2; last; } } } my $count; print 'Match ', ++$count, ": '$_'\n" foreach @matches;