Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: added hash entry in a subroutine is lost

Why is the hash empty on the second call of printHash?

my %hash = ();
addToHash(\%hash);
printHash(\%hash);

sub addToHash {
  my %hash = %{$_[0]};
  $hash{"test"} = "test";
  printHash(\%hash);
} 

sub printHash {
  print "printHash: \n";
  my %hash = %{$_[0]};
  foreach my $key (keys %hash) {
      print "key: $key, value: $hash{$key}\n";      
  }
}

Output:

printHash:

key: test, value: test

printHash:

like image 333
hansi Avatar asked Dec 19 '25 10:12

hansi


1 Answers

In

sub addToHash {
  my %hash = %{$_[0]};
  $hash{"test"} = "test";
  printHash(\%hash);
}

my %hash creates a new hash into which you copy the hash referenced by the argument. You want

sub addToHash {
  my $hr = $_[0];
  $hr->{"test"} = "test";
  printHash($hr);
}

in order to modify the original hash.

like image 190
chepner Avatar answered Dec 21 '25 03:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!