my @words; while ($content =~ /($word)/g) { push(@words, $1); } my @words_bi; my @words_tri; foreach (0..$#words) { next if $_ < 1; push(@words_bi, [ @words[$_-1 .. $_] ] ); next if $_ < 2; push(@words_tri, [ @words[$_-2 .. $_] ] ); }