Export PERL Array data to CSV

Hello,

I have a simple PERL script that connects to an Oracle DB, runs a SQL query and prints the array results into a table.  I need to give the option to export this array to a csv file.  What is the easiest way to add this functionality?  This is my  array output from the script after the SQL statement:

$sth->execute;
my $names = $sth->{'NAME'};
my $tbl_data = $sth->fetchall_arrayref;
print $cgi->table({-border=>1,-align=>'CENTER',},
           $cgi->Tr({-align=>'CENTER',-valign=>'TOP',-BGCOLOR=>'cccccc'},
           [
              $cgi->th($names),
              map { $cgi->td($_) } @$tbl_data,
           ]
           )
        );

Thanks for you help!
Tbone3434Asked:
Who is Participating?
 
wilcoxonCommented:
There is no really easy way to do it.  You'll need to create a second output routine that does the same data fetch from the database (or move the html output into a sub) and outputs as csv (rather than html).

For the output to csv code, it's just:

print join "\n", map { join(',', map { "\"$_\""' } @$_ } @$tbl_data;
0
 
Tbone3434Author Commented:
Thanks for you help on this Wilcoxon!  I am havinf some difficulty getting that to work though.  What else am I missing on this?  Even if this could just print to a CSV file on the server each time it ran rewriting the old data and a user could just click a link and download the file?  what do you think?  Again thanks for your help! :)
#!/usr/bin/perl

use DBI;

my $dbh = DBI->connect('dbi:Oracle:test','user','password',
                      { RaiseError => 1,AutoCommit => 0})
              or die "Database connection not made: $DBI::errstr";
{
my $sth = $dbh->prepare("SELECT * FROM test_name");
$sth->execute;
my $names = $sth->{'NAME'};
my $tbl_data = $sth->fetchall_arrayref;
print join "\n", map { join(',', map { "\"$_\""' } @$_ } @$tbl_data;


$dbh->disconnect(); }

Open in new window

0
 
wilcoxonCommented:
When you say you are having difficulty, what is it you are having trouble with?  Does the script produce the CSV file correctly and just isn't working as a CGI?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.