in reply to Replacing a given character starting with the xth occurence in a string

I would use tr///.
sub adv_tr { my ($str, $x, $from, $to) = @_; my $pos = 0; # find index of Xth "$from" ($pos = index($str, $from, $pos)) == -1 and return while $x--; eval "substr(\$str, $pos) =~ tr/\Q$from\E/\Q$to\E/"; }


japhy -- Perl and Regex Hacker
  • Comment on Re: Replacing a given character starting with the xth occurence in a string
  • Download Code

Replies are listed 'Best First'.
Re: Re: Replacing a given character starting with the xth occurence in a string
by MeowChow (Vicar) on May 21, 2001 at 10:30 UTC
    Eh, you didn't actually test this, did you? =)

    See my reply to bbfu above. You'd have to do something like:

    sub adv_tr { my ($str, $x, $from, $to) = @_; my $pos = -1; ($pos = index($str, $from, $pos + 1)) == -1 and return $str while $x +--; eval "substr(\$str, $pos) =~ tr/\Q$from\E/\Q$to\E/"; $str; }
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print