sub subst_str { my $match = shift; my $b = ... return "$match$b"; } .. $str =~ s/(]*>\s*\s*)[^<]*<\/endtag3>/subst_str($1)/gsie; # note the /e