use Template; sub foo { my $template = Template->new(); (my $text = $_[0]) =~ s/$_[1]/ my $output = ''; my @matches = map { substr($text, $-[$_], $+[$_] - $-[$_]) } 1 .. $#-; $template->process(\$_[2], { matches => \@matches }, \$output); $output /e; print $text; } foo("This is test 1\n", qr/test (.*)/, 'fish [% matches.1 %]');