tags:

views:

86

answers:

1

I am using IxHash to remember the insertion order of a hash. but when using clone to copy a hash i get an empty hash.

use strict;
use Switch;
use Data::Dumper;
use Clone qw(clone);
use Tie::Autotie 'Tie::IxHash';

our %h_basic_values;
my $t = tie our(%h_inner_hash), "Tie::IxHash";
my $t1 = tie our(%h_inner_hash1) , "Tie::IxHash";

%h_inner_hash = (
'in_1' => 'val_1',
'in_2' => 'val_2',
'in_3' => 'val_3'
);

%h_inner_hash1 = (
'innnn_1' => 'vallll_1',
'innnn_2' => 'vallll_2',
'innnn_3' => 'vallll_3',
);

$h_inner_hash{in_4}{inn_1} = "vall_1";
$h_inner_hash{in_4}{inn_2} = "vall_2";
$h_inner_hash{in_4}{inn_3} = "vall_3";
$h_inner_hash{in_4}{inn_4} = "vall_4";
$h_inner_hash{in_4}{inn_5}{innn_1} = 'valll_1';
$h_inner_hash{in_4}{inn_5}{innn_2} = "valll_2";
$h_inner_hash{in_4}{inn_5}{innn_3} = "valll_3";
$h_inner_hash{in_4}{inn_5}{innn_4} = "valll_4";

$h_inner_hash{in_4}{inn_5}{innn_5} = clone(\%h_inner_hash1);
print Dumper(\%h_inner_hash);

in $h_inner_hash{in_4}{inn_5}{innn_5} i am getting an empty hash.

+4  A: 

It's not a problem with Clone, or with the fact that %h_inner_hash1 is tied. It's a limitation of Tie::Autotie. From its perldoc:

BUGS

[...]

Assigning a reference

In the Tie::IxHash example, you cannot do:

$hash{jeff} = {
  age => 22,
  lang => 'Perl',
  brothers => 3,
  sisters => 4,
};

because that creates a hash reference, not an object of Tie::IxHash. This hash reference ends up being destroyed anyway, and replaced with a Tie::IxHash object that points to an empty hash.

As a means round it, you could manually copy %h_inner_hash1 key-by-key:

$h_inner_hash{in_4}{inn_5}{innn_5}{$_} = $h_inner_hash1{$_} for keys %h_inner_hash1;

or you could manually tie each layer of the hash to Tie::IxHash rather than using Tie::Autotie.

Philip Potter
Just to be clear - the quoted section from POD is under **BUGS** heading.
DVK
@DVK: thanks, I've edited it in.
Philip Potter