I am working with Perl and SQL and need certain data to be exported as a csv file. I also need it to work so that if the field contains a comma it doesn't confuse it and read it as two fields. The fields can contain " or any other special characters as well.
So what do I need to do for this?
Thanx!
#!/usr/bin/perluse DBI;
$dbh = DBI->connect(...);
$sth = $dbh->prepare("SELECT * FROM table_name");
open(CSV, "> file.csv");
while ( $array_ref = $sth->fetchrow_arrayref ) {
foreach my $col ( @$array_ref ) {
print CSV '"' . strip($col) . '", ';
}
print CSV "\n";
}
close(CSV);
$dbh->disconnect();
sub strip {
my $string = $_[0];
$string =~ s/\"/\\"/g;
$string =~ s/\\/\\\\/;
$string =~ s/,/\\,/g;
}