sub replace_split_1 { # pre-5.10 safe: no // operator, no regex extensions my ($string, # string to search/replace $srch, # search string (no regex metacharacters) $repl, # optional: replacement string (default: '') $n, # optional: number of replacements (default: infinite) ) = @_; # handle degenerate cases. return '' unless defined $string; return $string unless defined $srch && length $srch; # ??? # default replacement string: empty string. $repl = '' unless defined $repl; # avoid // (defined-or) operator # replace right-to-left if n is defined and < 0. my $replace_right_to_left = defined($n) && $n < 0; # split limit: one more than absolute of replacement count # unless count is undefined/infinite. my $limit = defined $n ? 1+abs($n) : -1; # split limit # reverse all strings if replacing right-to-left. if ($replace_right_to_left) { $_ = reverse for $string, $srch, $repl; } # split on meta-quoted search substring to specified limit. my @groups = split "\Q$srch", $string, $limit; # replace all instances of search substring. $string = join $repl, @groups; # return result with reversal reversed if needed. return $replace_right_to_left ? reverse $string : $string; } # end sub replace_split_1()