#!/usr/bin/perl # http://perlmonks.org/?node_id=1141535 use strict; use warnings; my $numwords = 40; $_ = "To be or not to be.\n"; # or read from file... my @previous; # holds the $numwords previous words s/(\w+)/ my $match = grep lc $1 eq lc, @previous; push @previous, $1; @previous > $numwords and shift @previous; $match ? "*$1*" : $1 /ge; print;