kulls,
There are lots of ways that you could do this. But firstly, you didn't say what you want to do with data_line[4|5|6]?
But anyway, lets assume that you want to ignore them. Then you could do something like:
use strict;
my (@fields, @data);
while (<DATA>) {
chomp;
my ($field, $value) = split;
next if !defined $value;
push @fields, $field;
push @data, $value;
}
my $insert = "INSERT INTO foo ("
. join(",", @fields)
. ") VALUES ("
. join(",", map { qq("$_") } @data)
. ");";
print "$insert\n";
__DATA__
col1 data_line1
col2 data_line2
col3 data_line3
data_line4
data_line5
data_line6
col4 data_line7
Update: Actually, don't do that - it's bad because it doesn't use placeholders. Here is a better method, following from the example given in the DBI recipes Tutorials.
my $fieldlist = join(",", @fields);
my $placeholders = join(",", map {'?'} @fields);
my $insert = qq{
INSERT INTO foo ($fieldlist)
VALUES ($placeholders)};
You would then pass your @data list to db->execute, eg
$dbh->execute(@data);
Cheers,
Darren :)
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.