# assuming the database handle in $dbh use Text::CSV_XS; sub save_table { my $tbl = shift; # it is up to you to check for SQL-injection on $tbl ... my $sth = $dbh->prepare ("select * from $tbl"); $sth->execute; my %rec; my @fld = @{$sth->{NAME_lc}}; $sth->bind_columns (\@rec{@fld}); my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, eol => "\n", always_quote => 1 }); $csv->print (*STDOUT, \@fld); # Print header, change STDOUT to file if required while ($sth->fetch) { $csv->print (*STDOUT, [ @rec{@fld} ]); } } # save_table