Perl - CodeGolf - Nested loops & SQL inserts

Posted by CheeseConQueso on Stack Overflow See other posts from Stack Overflow or by CheeseConQueso
Published on 2010-12-24T23:34:15Z Indexed on 2010/12/24 23:54 UTC
Read the original article Hit count: 281

I had to make a really small and simple script that would fill a table with string values according to these criteria:

  • 2 characters long
  • 1st character is always numeric (0-9)
  • 2nd character is (0-9) but also includes "X"
  • Values need to be inserted into a table on a database

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.

© Stack Overflow or respective owner

Related posts about perl

Related posts about efficiency