Ahem, I think the answer is probably VERY simple. If you say it works on the command line and when using it as a CGI script it prints out to the browser correctly, but the data file is not being saved the browser, then the answer is indeed simple: your script does not have permission to write the file.
The solution? try chmoding the cgi script 777 and then run it. It might work then, as some server configurations give your perl script the same file access permissions as the permissions of the script you are running. Otherwise, either you (assuming you are the server administrator) or the server administration will have to set up the Web Server up differently.
For the problem of system "main.cgi"; not working, use system "perl main.cgi"; instead, since main.cgi probably does not have execute permissions.