sub before_nth_char { my ($str, $c, $n) = @_; my $pos = -1; { $pos = index $str, $c, $pos + 1; return if $pos == -1; redo unless --$n == 0; return substr $str, 0, $pos; } } print before_nth_char("asdfasdfasdf", "a", 2), $/;