开发者

Problem storing a hash in DB using Storable::nfreeze in Perl

开发者 https://www.devze.com 2022-12-26 21:42 出处:网络
I want to insert a hash in the db using Storable::nfreeze but the data is not inserted properly. My code is as follows:

I want to insert a hash in the db using Storable::nfreeze but the data is not inserted properly.

My code is as follows:

%rec=();
$rec{'name'} = 'my name';
$rec{'address'} = 'my address';

my $order1 = new Order();
$order1->set_session(\%rec);
$self->createOrder($order1);

sub createOrder {
my $self  = $_[0];
my $order = $_[1];


# Retrieve the fields to insert into the database.
my $st = $dbh->prepare("insert into order (session,.......) values(?,........)");

my $session   = %{$order->get_session()};
$st->execute(&Storable::nfreeze(\%session),.....);
$st->finish();

}

sub getOrder
{
     ...

    my $session = &Storable::thaw( $ref->{'session'} );
    .....
}    

The thaw is working fine because I tested it withe some rows that have been inserted correctly, but when I try to get a row that was inserted using the createOrder subroutine, I get an error saying:

Storable binary开发者_运维百科 image v36.65 more recent than I am (v2.7) at blib/lib/Storable.pm (autosplit into blib/lib/auto/Storable/thaw.al) line 415

The error comes from the line that have thaw. The nfreeze did not store the hash properly.

Can someone point me to what I'm doing wrong in the createOrder subroutine?

I know the module version have nothing to do with the problem.


Your problem is probably improper dereferencing here:

my $session   = %{$order->get_session()};
$st->execute(&Storable::nfreeze(\%session),.....);

This should fix it:

my $session   = $order->get_session();
$st->execute(&Storable::nfreeze($session),.....);

Since ->get_sessionreturns a hash reference, when you dereferenced it in scalar context it was turning into a string that contains statistics on the hash. The hash %session is the empty package variable %main::session which you would have caught if you were running with use strict; use warnings;.

0

精彩评论

暂无评论...
验证码 换一张
取 消