in reply to cgi: malformed header from script. Bad header=

I do not see anything wrong in the code you provided.

Anyway, as written in CGI.pm documentation. You may have to use something like:

-type => "application/octet-stream"

for the attachment header to work.

try it & let me know.