I put a little effort into the Perl syntax to fix a couple of issues and hopefully make it more robust.
All Perl users are invited to try it out and leave some comments in order to find remaining issues.
If you find some issues, please provide some code snippets to help identify the culprit.