DBI doesn't seem to support array types (or maybe I just missed it) and PostgeSQL does. So, I wrote this routine to parse them out.

The way the postgresql arrays work is that the array is serialized into a string with comma delimited values, and enclosed in braces {}. text types are quoted in double quotes, and numbers are left bare. So to insert a list of lists, your SQL might look like this:

INSERT INTO tablename VALUES ( '{ {"this is 0,0", "this is 0,1"}, {"1,0"} }' )

So my question is, how would I go about making the following code more efficient? I already have some cute hacks, like the s/^{// and chop that work because of the unusual situation of having highly controlled input data. This is one of those cases where run speed is way more important than readability or maintainability because A) once finished there are no features to add, the problem domain will be saturated and B) I'm going to port it to PL/Perl and run it as a stored procedure in the database, so the users of the routine won't be able to mess with it directly anyway.

Here is the code:

sub de_postgresify_string { my $string = shift; return undef unless defined $string and length $string; $string =~ s/^\{// and chop $string; my @array = map { s/^\s+//; s/\s+$//; $_ } split /,/, $string; foreach my $chunk ( @array ) { if ( $chunk =~ /^\{/ ) { $chunk = [ de_postgresify_string( $chunk ) ]; next; } $chunk =~ s/^\"// and chop $chunk; } return @array; }

--
Snazzy tagline here

In reply to Parsing PostgreSQL array types by Aighearach

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.