http://www.perlmonks.org?node_id=1232846


in reply to Help formatting text to delimited text in file

Somedays one feels like being a "jerk" so
#!/usr/bin/env perl use Data::Dumper; use 5.14.0; my @data=( q{^46004 % Tamerlane.| Tamerlane - Sheridan; Bajazet - Barry; +Moneses - A Gentleman; Arpasia - Mrs. Furnival; Selima - Mrs. Elmy; + +} ,q{^46005 % Hamlet.| Hamlet - Sheridan; Polonius - J. Morris; +Laertes- Lacy; Ophelia- Mrs. Storer; Queen - Mrs. Furnival; +} ); local $"='","';#" for (@data) { my %c_h; if (m{^\^(.+?) % (.+?)\.\|(?{$c_h{1}=$1; $c_h{2}=$2;}) ?(?:(.+?) * +- *(.+?); ?(?{$c_h{3}=$3;$c_h{4}=$4; say qq{"@c_h{qw(1 2 3 4)}"}}))*} +) { }; }; __DATA__
which gives on my machine
"46004","Tamerlane","Tamerlane","Sheridan" "46004","Tamerlane","Bajazet","Barry" "46004","Tamerlane","Moneses","A Gentleman" "46004","Tamerlane","Arpasia","Mrs. Furnival" "46004","Tamerlane","Selima","Mrs. Elmy" "46005","Hamlet","Hamlet","Sheridan" "46005","Hamlet","Polonius","J. Morris" "46005","Hamlet","Laertes","Lacy" "46005","Hamlet","Ophelia","Mrs. Storer" "46005","Hamlet","Queen","Mrs. Furnival"
See A bit of magic: executing Perl code in a regular expression. Of course, you might as well do something like this (and go straight to the database):
#!/usr/bin/env perl use Data::Dumper; use DBI; use 5.14.0; use if ($ENV{DBG} || $ENV{DEBUG}),'Devel::Include','keep',$ENV{MASK} ? + $ENV{MASK} : '#=#'; my @data=( q{^46004 % Tamerlane.| Tamerlane - Sheridan; Bajazet - Barry; +Moneses - A Gentleman; Arpasia - Mrs. Furnival; Selima - Mrs. Elmy; + +} ,q{^46005 % Hamlet.| Hamlet - Sheridan; Polonius - J. Morris; +Laertes- Lacy; Ophelia- Mrs. Storer; Queen - Mrs. Furnival; +} ); my $dbh=DBI->connect('dbi:SQLite:dbname=test.sqlite','','',{ PrintErro +r=>1, RaiseError=>1 }); $dbh->do(<<"__CREATE__"); CREATE TABLE titles ( number integer, name text); __CREATE__ $dbh->do(<<"__CREATE__"); CREATE TABLE roles ( number integer, role text, actor text); __CREATE__ my %sth; $sth{title}=$dbh->prepare(<<"__TITLE__"); INSERT INTO titles (number,name) VALUES (?,?); __TITLE__ $sth{role}=$dbh->prepare(<<"__ROLE__"); INSERT INTO roles (number,role,actor) VALUES (?,?,?); __ROLE__ local $"='","';#" for (@data) { if (m{^\^(.+?) % (.+?)\.\|(?{$sth{title}->execute($1,$2)}) ?(?:(.+ +?) *- *(.+?); ?(?{$sth{role}->execute($1,$3,$4)}))*}) { }; }; $dbh->disconnect;