[ale] OT perl hash help

Mike Fletcher fletch at phydeaux.org
Mon Aug 4 11:57:12 EDT 2008


David Hamm wrote:
> Hi,
>
> I'm trying to copy a hash from a hash reference and failing.  Could someone 
> offer some guidance off line?  Thanks.
>
> # print a value in the original Hash Ref 
> print "$FC->{ IpConfig }{ BCA }\n";  
>
> # try to copy the hash ref to a has
> my( %hcopy ) = %$FC;
> my( $hcopyref ) = \%hcopy;
>
> print "$FC\n";
> print "$hcopyref\n";
>
> This bit of code produces:
> HASH(0x26892c)
> HASH(0x113bc4)
>
> But $hcopyref->{ Ipconfig }{ BCA } = 50;  changes the value in both hashes.
>   
Because while you've copied the contents of the first level, the values 
it contains are still references to the same second level hashes (your 
original and copy both point to the same hash for the key 'Ipconfig').

You either need to walk the second level and make copies at that depth 
as well, or more generically use some sort of serialization (Storable, 
Data::Dumper, YAML::Syck) to make a deep copy instead.

See also http://perldesignpatterns.com/?CloningPattern



More information about the Ale mailing list