0

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
yegor256
  • 102,010
  • 123
  • 446
  • 597
  • The best solution is still to use a lexically scoped variable, and not try to reuse the same exact variable again. I'm sorry. – TLP Dec 11 '22 at 17:32
  • 1
    You can make a shallow copy of a hash using assignment: `my %h2 = %h`, see also [this](https://stackoverflow.com/a/7083603/2173773) answer for copying a hash ref – Håkon Hægland Dec 11 '22 at 18:00

1 Answers1

3

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.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174