danj35 has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I'm familiar with Perl's substr and index functions, although I can't seem to find a simple way to combine them in order to match to a specific index within a block of text and then replace this substring with a new piece of text. The only simple way I can think to do it would be using regular expressions, although there's a danger that I'll end up replacing the subtring if it occurs more than once.

At present I have a hash with, 'trigger_start', 'trigger_end' and 'trigger_text' for the substring I'm interested in each time. I'm iterating through the substrings backwards so that any replaced text won't need to offset any of the other substring positions.

Thanks very much

Replies are listed 'Best First'.
Re: Replace text at given index
by Ratazong (Monsignor) on Jun 06, 2011 at 13:43 UTC
    Have you considered the "replacement-option" of substr? Have a look at the following example, which replaces "fox":
    my $text = "the quick brown fox likes jumping"; my $pos1 = index ($text, "fox"); my $length = 3; substr( $text, $pos1, $length, "aligator"); print $text,"\n";
    HTH, Rata
Re: Replace text at given index
by rovf (Priest) on Jun 06, 2011 at 13:49 UTC

    Maybe something like

    substr($s,rindex($s,$searchstring),length($searchstring))=$replacestri +ng;
    ? However, this assumes that you *do* find the searchstring. If the searchstring is not found, rindex returns -1. You would have to catch this with eval.

    Note that my solution would start looking for the searchstring always from the end. In particular, it would also consider the replacement you have done earlier. If you don't want to do this, things get even more complicated.
    -- 
    Ronald Fischer <ynnor@mm.st>