在Perl中深度复制哈希哈希的最佳方法是什么?
Possible Duplicate:
What's the best way to make a deep copy of a data structure in Perl?
在我自己编写代码并重新设计轮子之前,如何在不复制哈希引用的情况下复制哈希哈希?
Before I start coding this myself and reinventing the wheel, how do you copy a hash of hashes without duplicating the hashrefs?
我正在通过 Config :: General 阅读散列的哈希值>.即数据结构为:
I'm reading a hash of hash of hashes via Config::General. i.e., the data structure is:
my %config = ( group => { item1 => { foo => 'value',
bar => 'value',
},
item2 => { foo => 'value',
bar => 'value',
},
item3 => { foo => 'value',
bar => 'value',
},
},
);
然后我通过取消引用来从配置中拉出我的组,并在重写配置文件之前在运行时更改内容:
I then pull my group from the config by dereferencing it and change the contents at runtime prior to rewriting the config file:
my %group = %{$config{'group'}};
问题是我需要检查是否已进行更改,并对系统的文件结构进行相关更改.我无法通过检查来做到这一点:
The problem is that I need to check to see if changes were made and make associated changes to the system's file structure. I can't do this by checking:
if ($group{'item1'}{'foo'} ne $config{'group'}{'item1'}{'foo'}) {
### Stuff!
}
as $group{'item1'}
和$config{'group'}{'item1'}
都是完全相同的hashref.
as $group{'item1'}
and $config{'group'}{'item1'}
are both the exact same hashref.
现在,简单地重新解析配置文件,然后在将其保存到磁盘之前将从磁盘中解析的副本与编辑后的版本进行比较应该是微不足道的,但我敢肯定,有一种方法可以嵌套取消对a的引用复杂的数据结构,复制哈希引用的内容,而不是简单地复制引用本身.粗略地检查CPAN并没有发现任何问题.我想念什么?
Now while it should be trivial to simply re-parse the config file, and compare the parsed copy from the disk against the edited version just before saving to disk, I'm sure there's a way to to a nested dereference of a complex data structure, copying the contents of the hash refs and not simply copying the references themselves. A cursory examination on CPAN doesn't turn anything up. What am I missing?
基准
得到我的答案:
#!/usr/bin/perl
use Benchmark qw(:all) ;
use Storable qw(dclone);
use Clone qw(clone);
my %config = ( group => { item1 => { foo => 'value',
bar => 'value',
},
item2 => { foo => 'value',
bar => 'value',
},
item3 => { foo => 'value',
bar => 'value',
},
},
);
my $ref = $config{'group'};
timethese(100000, {
'Clone' => sub { my %group = %{ clone $ref }},
'Storable' => sub { my %group = %{ dclone $ref }},
});
导致:
Benchmark: timing 100000 iterations of Clone, Storable...
Clone: 2 wallclock secs ( 2.26 usr + 0.01 sys = 2.27 CPU) @ 44052.86/s (n=100000)
Storable: 5 wallclock secs ( 4.71 usr + 0.02 sys = 4.73 CPU) @ 21141.65/s (n=100000)
use Storable qw(dclone);
$group2 = dclone(\%group);