简体   繁体   English

我们可以在捆绑哈希上使用Storable的存储方法吗?

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

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. 但这不起作用 - 文件被创建,但它只有50个字节大小,当我使用retrieve()时,我得到一个空哈希。

I tried using Tie::IxHash::Easy (because my hash is a hash of hashes) but to no avail. 我尝试使用Tie :: IxHash :: Easy(因为我的哈希是散列哈希),但无济于事。 Any help? 有帮助吗?

You need to tie the hashref before you populate it 在填充hashref之前,您需要绑定hashref

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
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM