Ah, well then. If you have control over the delimiters, then that definitely makes things easy. Let's go with what you used there, but always use a single | to delimit fields instead of doubling it between the second and third fields (when a third field is present).

Some basic code to split all the data up and insert it into a database would look something like:

# This code assumes that you've already initialized a # database handle, $dbh, and your string of data is in # $input my $sth = $dbh->prepare('INSERT INTO my_table (field1, field2, field3) + VALUES (?, ?, ?);'); my @records = split '&', $input; foreach my $record (@records) { my @fields = split '\|', $record; $sth->execute(@fields); }
If there are only two fields in the record, the database placeholders (the ?s in the SQL text) should convert the nonexistent third element of @fields into a NULL in the database. If you get an error about not having enough values to bind, replace both occurrences of @fields with ($field1, $field2, $field3) to force it to always pass three values. (The code is untested, but simple enough that I should have gotten it right...)

Note the backslash escape in the second split. The | character is special and you'll get every character individually if you split on '|' instead of '\|'.


In reply to Re^3: Extract Elements from an array and insert into database by dsheroh
in thread Extract Elements from an array and insert into database by parshtml

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.