Hi all, please help me
I have a csv file and I need to create an application using Perl to read and generate SQL statements but I faced a problem.
Lets say my data is as follow:
a, asd, 123
b, asd, 234
c, asd, 345
My result will be:
Insert into person_info VALUES("a","asd","123");
Insert into person_info VALUES("b","asd","234");
Insert into person_info VALUES("c","asd","345");
But if my data is:
a, a"s"d, 123
b, asd, 234
c, as"d", 345
My result will become:
Insert into person_info VALUES("a","a","s","d","123");
Insert into person_info VALUES("b","asd","234");
Insert into person_info VALUES("c","as","d","345");
How do i make it such a way that result will be:
Insert into person_info VALUES("a","a"s"d","123");
Insert into person_info VALUES("b","asd","234");
Insert into person_info VALUES("c","as"d"","345");
My code currently is as follow:
$csv = "test.csv";
open(DAT, $csv) || die("Cannot Open File");
while (<DAT>) {
my @new = ();
push(@new, $+) while $_ =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",?
| ([^,]+),?
| ,
}gx;
push(@new, undef) if substr($_, -1,1) eq ',';
my $string = format_string(@new);
my $query = qq{Insert into person_info VALUES ($string)};
print $query, "\n";
}
sub format_string {
my $string;
foreach (@_) {
if (/[^\d]/) {
$string .= qq{"$_",};
} else {
$string .= qq{$_,};
}
}
return substr($string, 0, -1);
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.