in reply to Premature end of script headers

You might be getting that error because your program sends an error message before it sends the "Content-type" string.

You could try moving the print closer to the start of the program, but even better would be

use CGI::Carp qw/fatalsToBrowser/;
That should make all the error messages show in your browser window.