Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a shallow copy of a Perl hash reference?

I want to push a reference to a hash. By that I mean I want to push a reference to a new hash that is a shallow copy of the hash I am given.

How do I create the shallow copy?

like image 643
Don Avatar asked Jan 08 '10 23:01

Don


1 Answers

Just copy it:

 my %copy = %$hash;

If you want another reference, just expand the original reference in the anonymous hash constructor:

 my $copy = { %$hash };

For those wondering about shallow copies: this sort of assignment only makes new values for the top level keys. Any values that are references will still be the same reference in the new hash. That is, you can replace a value in the new hash without changing the original hash. If you merely change the value, such as pushing a new item onto an anonymous array value, both hashes get the change because they share the same reference. As such, shallow copies are usually not what you want.

like image 50
brian d foy Avatar answered Oct 07 '22 22:10

brian d foy