$num = 4; for($str=~/.?/g){ $h{space} += !/\S/; $word .= $_ if $h{space} == $num-1 && /\S/ .. !/\S/ } print $word;