I need a little help with a perl script im writing. The idea of the perl script is to write the output of an SQL query to a document in HTML format and then display an html page telling the user that the file has been written.
The script i have so far looks like this:
#!/usr/bin/perl -w
# do some bugzilla stuff (not important)
use strict;
require "globals.pl";
use Bugzilla::Constants;
my $cgi = Bugzilla->cgi;
my $dbh = Bugzilla->dbh;
my $vars = {};
my $user = Bugzilla->login(LOGIN_REQUIRED);
#execute the query
my $results = $dbh->selectall_arrayref('select bug_id, creation_ts,short_desc from bugs where product_id IN (select id from products where classification_id=2)');
#open test.doc for writting
open(MYOUTFILE, ">test.doc");
print MYOUTFILE "Content-type: text/html\n\n";
print MYOUTFILE "<HTML><HEAD>";
print MYOUTFILE "<TITLE>CGI Test</TITLE>";
print MYOUTFILE "</HEAD>";
print MYOUTFILE "<BODY><H2>Test bug page</H2>";
print MYOUTFILE "<table>";
print MYOUTFILE "<tr><th>Defect Number</th><th>Date</th><th>Short Description</th></tr>";
foreach my $quipref (@$results) {
print MYOUTFILE "<tr>";
my ($bug_id,$creation_ts,$short_desc) = @$quipref;
print MYOUTFILE "<td>$bug_id</td>";
print MYOUTFILE "<td>$creation_ts</td>";
print MYOUTFILE "<td>$short_desc</td>";
print MYOUTFILE "</tr>";
}
print MYOUTFILE "</table>";
print MYOUTFILE "</BODY></HTML>\n";
#close test.doc
close(MYOUTFILE);
#write the html ouput to browser
print "Content-type: text/html\n\n";
print "<HTML><HEAD>";
print "<TITLE>CGI Test</TITLE>";
print "</HEAD>";
print "<BODY><H2>File test.doc written</H2></BODY>";
The script sucessfully produces the HTML output at the end but no file is written, anyone have any idea what i'm doing wrong.
Thanks in advance, stu.
You should also test for successful writing of files:
open(MYOUTFILE, ">myfile") ¦¦ die "Cannot open file: $!\n";
Bill
open(MYOUTFILE, ">test.doc") or &error("Cannot write test.doc: $!");
Then add this error routine at the end of your script:
sub error {
my ($err);
$err = shift(@_);
print "Content-type: text/html\n\n";
print "an error has ocurred: $err";
exit 0;
}
The operator $! will hold system errors. I will bet it says "permission denied." :-)
You could try creating an empty test.doc and set the permissions on it to world-write (777) before executing the script.
Any time you open a file, read a database, do anything at all - add an error hook that can clue you in to what's going wrong.