Here are a few suggestions to make the code clearer and perhaps then garner more helpful answers:
- use strict
- use warnings
- use Test::More instead of trying to roll your own testing framework
- Avoid prototypes
- Avoid localising $_
- Avoid capture groups which you never use
- Avoid P. It's fine in your own code but here it is unnecessary (or would be if you used Test::More) and is another barrier to help.
- Pick a formatting scheme and stick to it. Random whitespace doesn't help.
In summary, help us to help you.