Build a regex and use placeholders.

#!perl use strict; use DBI; use Data::Dump 'pp'; my $dbh = get_dbh(); # connect # field names my @fname = qw(QB RB1 RB2 WR1 WR2 WR3 TE FLEX DST); my $fld = join ',',@fname; # placeholders my $ph = '?'.(',?' x $#fname); # build regex from field names without numbers my $re = join '\s*(.*?)\s*',(map { s/\d// ; $_}@fname),'' ; # prepare my $sql = "INSERT INTO test_table (ID,$fld) VALUES (NULL, $ph)"; my $sth = $dbh->prepare($sql); # input data while (<DATA>){ if ( my @f = /$re$/ ){ $sth->execute(@f); } } # print results pp $dbh->selectall_arrayref('SELECT * FROM test_table'); # connect / create test table sub get_dbh{ my $database = "test"; my $user = "user"; my $pw = "password"; my $dsn = "dbi:mysql:$database:localhost:3306"; my $dbh = DBI->connect($dsn, $user, $pw, { RaiseError=>1, AutoCommit=>1 } ); #$dbh->do('drop table test_table'); $dbh->do(" CREATE TABLE IF NOT EXISTS test_table ( ID int(11) NOT NULL AUTO_INCREMENT, QB varchar(45) DEFAULT NULL, RB1 varchar(45) DEFAULT NULL, RB2 varchar(45) DEFAULT NULL, WR1 varchar(45) DEFAULT NULL, WR2 varchar(45) DEFAULT NULL, WR3 varchar(45) DEFAULT NULL, TE varchar(45) DEFAULT NULL, FLEX varchar(45) DEFAULT NULL, DST varchar(45) DEFAULT NULL, UNIQUE KEY ID_UNIQUE (ID) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); #$dbh->do('delete from test_table'); return $dbh; } __DATA__ QB Carson Palmer RB Chris Ivory RB Eddie Lacy WR A.J. Green WR John Br +own WR Davante Adams TE Martellus Bennett FLEX Jeremy Hill DST Panthe +rs
poj

In reply to Re: Recommendations for breaking up string? by poj
in thread Recommendations for breaking up string? by jdlev

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.