Search code examples
perl

How to make a shallow copy of a hash?


I have a hash, which is filled up with data. I add it to an array. Then, I want to modify my hash, but make sure that what is in the array remains untouched. I'm trying this, doesn't work:

my @a;
my %h;
%h{foo} = 1;
push(@a, \%x);
%h = (); # here I clean the hash up
# but I want the array to still contain the data

I feel that I need to make a copy of it before adding to the array. How? I don't need a deep copy, my hash contains only strings.


Solution

  • I don't need a deep copy, my hash contains only strings.

    Then you could make a shallow copy of the hash:

    my @a;
    my %h;
    %h{foo} = 1;
    my %copy_of_h = %h;
    push(@a, \%copy_of_h);
    %h = ();
    

    See also this answer for how to copy a hash ref. For more on Perl data structures, see perldsc and perldata.