I had to make a really small and simple script that would fill a table with string values according to these criteria:
The program would execute:
insert into table (code) values ('01');
insert into table (code) values ('02');
insert into table (code) values ('03');
insert into table (code) values ('04');
insert into table (code) values ('05');
insert into table (code) values ('06');
insert into table (code) values ('07');
insert into table (code) values ('08');
insert into table (code) values ('09');
insert into table (code) values ('0X');
And so on, until the total 110 values were inserted.
My code (just to accomplish it, not to minimize and make efficient) was:
use strict;
use DBI;
my ($db1,$sql,$sth,%dbattr);
%dbattr=(ChopBlanks => 1,RaiseError => 0);
$db1=DBI->connect('DBI:mysql:','','',\%dbattr);
my @code;
for(0..9)
{
$code[0]=$_;
for(0..9)
{
$code[1]=$_;
insert(@code);
}
insert($code[0],"X");
}
sub insert
{
my $skip=0;
foreach(@_)
{
if($skip==0)
{
$sql="insert into table (code) values ('".$_[0].$_[1]."');";
$sth=$db1->prepare($sql);
$sth->execute();
$skip++;
}
else
{
$skip--;
}
}
}
exit;
I'm just interested to see a really succinct & precise version of this logic.
use DBI;$d=DBI->connect('DBI:mysql','','',{RaiseError=>1});for$a(0..9){for$b(0..9,'X'){$d->do("insert into table values('$a$b')");}}
use strict;use DBI;my$d=DBI->connect('DBI:mysql','','',{RaiseError=>1});for my$a(0..9){for my$b(0..9,'X'){$d->do("insert into table values('$a$b')");}}
use strict;use DBI;
my $d=DBI->connect('DBI:Informix:stores','','',{RaiseError=>1});
foreach my $a (0..9)
{
foreach my $b (0..9, 'X')
{
$d->do("insert into table values('$a$b')");
}
}
Given:
create table table(code char(2) not null);
And the Perl:
use strict;
use DBI;
my $d=DBI->connect('DBI:mysql','','',{RaiseError=>1});
my $h=$d->prepare("insert into table(code)values(?)");
foreach my $a (0..9)
{
foreach my $b (0..9, 'X')
{
$h->execute("$a$b");
}
}
I tested with Informix, so the connect string I actually used was "DBI:Informix:stores
".
This solution is still readable - and because of the RaiseError, error-proofed (unless you want to add a transaction too).
Code Golfing it, it becomes (182 characters):
use strict;use DBI;my$d=DBI->connect('DBI:mysql','','',{RaiseError=>1});my$h=$d->prepare("insert into table(code)values(?)");for my$a(0..9){for my$b(0..9,'X'){$h->execute("$a$b");}}