in reply to formatting text

Two quick points first.

/[\d\D]/? That looks like a weird way to say /./s or even /(?s:.)/.

for (<IN>) is similar to while (<IN>) except it takes way more memory since it reads the entire file into memory. Use while (<IN>).

Now back to the question,

open ...; open ...; $/ = ''; while (<IN>) { s/^\s+//; s/\s(?=\s)//g; print OUT; }

Or as a one-liner

perl -pe"BEGIN{$/=''} s/^\s+//; s/\s(?=\s)//g" test.txt > test.out

I'm sure there are many HTML formatters out there, though. You'd probably be better off using one of them.