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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With