my $test = "< a> a "; for ($test) { my $count = 0; s{(.)}{ $count++ if $1 eq '<'; $count-- if $1 eq '>'; $count ? uc $1 : $1; }ge; } print $test;