my $str="hello there bob smith and more words"; my $num_words=5; if (my ($words) = $str=~ /((?:\w+(?:\W+|$)){$num_words})/) { print $words; }