In Perl 5.20 I need to run a regular expression on a substring without copying it into a new string. So some equivalent to `$str[$to]` in the C language.

The reason is that it is executed in a loop and if it each time copies the string so the resulting code is `O(n^2)` while what without the copying it would be just `O(n)`. So with an input of 2MB string it is unusable.

Alternatively, I will welcome a suggestion on how to rewrite the code: I need to do a search and replace using a lookup table.

Example input

```
$str: "abcde"
$tbl: {ab=>"xy", bc=>"rq", e=>"a"}
$reg: qr/ab|bc|e/
expected output: xycda

```

This is my current code that runs fine for short strings, but it does not finish for large ones:

```
#translate $str: if $reg match found, replace the match with a value in $tbl hash that corresponds to the match
sub internalEncode {
    my ($str, $tbl, $reg) = @_;
    my $res="";
    my $prevTo = 0;
    my $to = 0;
    #the substr($str,$to) makes it slow; in C with 0 terminated strings
    #I would need to write here something like: $str[$to]
    while (substr($str,$to) =~ $reg) {
        my $match = $&;
        my $from = $prevTo + $-[0];
        $to = $prevTo + $+[0];
        $res .= substr($str,$prevTo,$from - $prevTo);
        $res .= $tbl->{quotemeta $match};
        $prevTo = $to;
    }
    $res .= substr($str,$prevTo);
    return $res;
}

```