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?
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.
精彩评论