For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > May 2006 > How to assign a hash of array to another hash









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author How to assign a hash of array to another hash
mohamad.ridha@intel.com

2006-05-26, 6:58 pm

Hi all,

I am trying to write a simple script but stuck with one problem on how
to assign a hash of array to another hash.

I have this hash named "record" that consists of two keys "recinfo" and
"recbody" and each key is assigned to hold an array of strings that
have been filled with values. The following code seems to work:

$record {"info"} = [ @recinfo ];
$record {"body"} = [ @recbody ];

But then I need to implement another hash named "recordlist" that has
variable "$recid" as keys, and each key will hold a "record" hash
above. I tried to use the following statement to assign the "record"
that has already filled with values to "recordlist" but to no avail.

$recordlist {"$recid"} = { %record };

Does anyone how to solve this problem?

Thanks in advance!

--Ridha

usenet@DavidFilmer.com

2006-05-27, 3:58 am

mohamad.ridha@intel.com wrote:
> I am trying to write a simple script but stuck with one problem on how
> to assign a hash of array to another hash.


The "trouble" is that Perl is doing EXACTLY what you tell it to do - it
is making an identical (EXACTLY identical) copy of the hash. The
"problem" is that the hash doesn't really have arrays as values
(because both the key and value of a hash must be scalars) - it has
array REFERENCES as values. So you get a copy of the hash, and a copy
of the array references, which point to the same data. This is called
"shallow cloning" and that's not what you want.

What you want is "deep cloning," where you copy the not just the values
(the references), but the data structure those references, um,
reference. To do this, you can use the dclone method of the Storable
module (a standard Perl module).

See:

perldoc -q copy
"How do I print out or copy a recursive data structure?"

--
http://DavidFilmer.com

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com