Can we use Storable's store method on a tied hash?

240 views Asked by At

Tried to store a hash reference in a Storable file and it worked fine. However I also had a requirement to keep the keys in a sorted order - so I used the following

tie %$hashref, 'Tie::IxHash'; store $hashref, $filename;

But this doesn't work - the file gets created but its only 50 bytes in size and when I use retrieve(), I get an empty hash.

I tried using Tie::IxHash::Easy (because my hash is a hash of hashes) but to no avail. Any help?

1

There are 1 answers

0
KeepCalmAndCarryOn On BEST ANSWER

You need to tie the hashref before you populate it

use strict; use warnings;
use Storable;
use Tie::IxHash;
use Data::Dumper;

my $filename= 'xxx';

my $hashref;
tie %{$hashref}, 'Tie::IxHash';
$hashref->{b}={c=>2, d=>{e=>3}};
$hashref->{a}=1;

print Dumper(before=>$hashref);

store $hashref, $filename;

print Dumper(after=>retrieve('xxx'));

returns

$VAR1 = 'before';
$VAR2 = {
          'b' => {
                   'c' => 2,
                   'd' => {
                            'e' => 3
                          }
                 },
          'a' => 1
        };
$VAR1 = 'after';
$VAR2 = {
          'b' => {
                   'c' => 2,
                   'd' => {
                            'e' => 3
                          }
                 },
          'a' => 1
        };