First of all, it is tremendously important that you use secure tainted mode (-T flag). Writing files based upon user input is a huge potential security risk, and now you simply can't publish unsecure code on the internet anymore without having it explode to your face right away.
Second, you probably need to figure out permissions properly.
Third you show us the code that works, not the code which isn't working. It's hard to guess what's wrong in code you didn't show...
Fourth I advise you to first read Ovid's CGI course and also check Perlmod documentation, I guess you're not getting the concept of namespaces and variable scoping right.