My first perl6 code

Like everybody else, I've been reading about Perl6, lurking in #perl6 and just trying to keep up with the progress. But in real life, most of us need to turn out Perl5 code for a living. Of course, we love it (well, I do), but it could be fun to have at least a line or two of Perl6 code under the belt before rakudo *.

So today I tried to jump head first into a problem I wanted solved, connecting to PostgreSQL from Perl6. I'd noticed that there is a Pg.pir in parrot, so I thought it would be possible to use that. It turned out that it is possible, but it required a lot of guessing and even more help from #irc (mainly moritz, who also identified and fixed (r47900) a bug in Parrot in a matter of minutes). omg people are helpful there!

Later I rewrote it as a class and can now execute PostgreSQL stuff. Not sure if it's useful in any other context, but at least I now know that it can be done.

I don't dare to measure the performance, but here's the code.

class PgTest {
	has $!dbh;

method BUILD {
pir::load_bytecode("Pg.pir");
my $pg = pir::new__pS('Pg');
$!dbh = $pg.connectdb('');
}

method do ($sql) {
say $sql;
my $res = $!dbh.exec($sql);
return if $res.ntuples < 0;

my @rows;
for 0..$res.ntuples-1 -> $row {
my @cols;
for 0..$res.nfields-1 -> $col {
push @cols, $res.getvalue($row, $col);
}
push @rows, [@cols];
}
return @rows;
}
};

my $db = PgTest.new;
say $db.do("INSERT INTO parrot_tbl (foo,bar) VALUES ('bah','buh') RETURNING id;").perl;
say $db.do('SELECT * FROM parrot_tbl;').perl;

do returns an AoA of the result. Can this be used in FakeDBI? I doubt it, I think there are others, and more efficient, ways to accomplish the same.

Leave a comment

About kaare

user-pic I blog about Perl and stuff.