Since it's been a while and no one has replied yet, I figured I'd offer some general advice which might make it easier for others to offer specific help:
Post your exact actual output.
Post your expected output.
Reduce your code as much as possible while still reproducing your error condition. Do you really need those 20 lines for $ARGV?