Created
May 29, 2015 18:32
-
-
Save belden/f1cf4db89270cd43daad to your computer and use it in GitHub Desktop.
Shows how to correctly de-sparsify a Perl array for storage into a postgresql 'array' data type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env perl | |
| use strict; | |
| use warnings; | |
| use Data::Dumper; | |
| my @sparse; | |
| $sparse[0] = 'start'; | |
| $sparse[3] = undef; | |
| $sparse[5] = 'end'; | |
| my @storeable1 = map { $sparse[$_] } grep { defined $sparse[$_] } 0..$#sparse; | |
| my @storeable2 = map { $sparse[$_] } grep { exists $sparse[$_] } 0..$#sparse; | |
| print Dumper +{ | |
| with_defined => \@storeable1, | |
| with_exists => \@storeable2, | |
| }; | |
| __END__ | |
| $VAR1 = { | |
| 'with_defined' => [ | |
| 'start', | |
| 'end' | |
| ], | |
| 'with_exists' => [ | |
| 'start', | |
| undef, | |
| 'end' | |
| ] | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The bits to know here are:
@sparseinto a PostgresqlARRAYcolumn, you'll get an exception (potentially a core dump, it's been a few years since I've done this): the sparse array doesn't get serialized from Perl -> Postgresql in a way that's friendly to Postgresql.definedto de-sparsify your array, then you'll throw away information:undefvalues will get pulled out, so won't turn intoNULLvalues at the correct relative position within the PostgresqlARRAY.So use
existswhen desparsifying your arrays instead.