Problem storing a hash in DB using Storable::nfreeze in Perl
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_session
returns 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;
.
精彩评论