Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing object on the DB and retrieving it

I have a perl object (reference to array of references) like the below:

my $a = [ [$a, $ab, $c ], [$a, $b, $c] ] ;

and need to store it on the DB then retrieve it.

Could someone suggest a good mechanism to serialize even to compress it and then store it on the DB? Then deserialize it and use it in the code?

like image 897
smith Avatar asked Mar 06 '12 09:03

smith


1 Answers

You may use any of the known serializers, e.g. JSON::XS or Storable. Storable is better if you want to retrieve references as references, not as copies of values. Then save a serialized object in the field of any type (VARCHAR, BLOB, ...) that satisfy storage requirements.

use Storable qw(nfreeze thaw);
use DBI;

# ... connect to database
# Store
my $data = [ [$a, $b, $c ], [ $a, $b, $c ] ];
my $bytestream = nfreeze $data;
$dbh->do('insert into table (field) values(?)', undef, $bytestream);

# Retrieve
$bytestream = $dbh->selectrow_array('select field from table where ...');
$data = thaw $bytestream;

Additionally, you can compress $bytestream, for example, via IO::Compress::Gzip

my $bytestream = gzip nfreeze $data;
like image 127
Ali Avatar answered Sep 23 '22 06:09

Ali