sub ucfirst_every_word { my $s = shift; $s =~ s{\b(\w+)\b}{ucfirst(lc($1))}eg; return $s; } $text =~ s/(= .*?KAPITEL.*? =)/ucfirst_every_word($1)/eg;