#!/usr/bin/perl -w use strict; my $str = 'abcadefaghi'; my $pat = '(a.)'; my $repl = '\u$1 '; $str =~ s/$pat/ my @save = (undef, $1, $2, $3, $4, $5, $6); $repl =~ s{\$$_}{$save[$_]}g for 1..6; $repl; /eg; print "$str\n";