sub pre_nth { my ($str, $char, $n) = @_; return join("", (split /(?=$char)/, $str)[0.. $n-1]); } print pre_nth("this q is the q of the q which quickly quoth he.", q => 3);