my $text = "This is a test for the word blue more things blue and then some very large text with a lot of things blue and done"; my $words_to_go = 0; my @keeper = (); while($text =~ /(\w+)/g) { if($1 eq "blue") { if(! $words_to_go) { print "$_ " for @keeper; } print "$1 "; $words_to_go = 5; } elsif($words_to_go) { $words_to_go--; print "$1 "; } else { push @keeper, $1; shift @keeper if @keeper > 5; } }