in reply to commenting regular expressions?

You need to add the /x modifier to your regexes.

Updated: as pointed out by a couple of others, you need to add it to each qr{...}x statement, not to the s//.

$$contents =~ s/$pattern/++$k && $replacement/gex;

</ajdelore>