my $str = 'Fsih my test variable is fsihd or is it gfsih or gfsihd fsih'; # 1111 2222 3333 4444 my $substr = 'fsih'; my $replace = 'fish'; my $instance = 3; # 3rd print("$str\n"); my $pos = -length($substr); for (;;) { last if !$instance--; $pos = index($str, $substr, $pos + length($substr)); last if $pos < 0; } substr($str, $pos, length($substr), $replace) if $pos >= 0; print("$str\n");