I'm happy to send you my hourly rate for doing this work for you.
Otherwise, you've got half-working code of your own, several references to what is likely wrong with it, links to the documentation wherein you will find your answers, and a completely working hunk of code using a different approach.
s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)