This code runs fine out of apache with one fix - your missing a closing } at the end of your first code block to close the else statement. (I also removed your version requirements for LWP,etc, as I'm not as fancy as you ;) ). If after that it still doesn't work right from the command line, then I would suspect its your command line syntax that's at fault, not the rest of the code.
"I have never written bad code. There are merely unanticipated features."