perl: added hash entry in a subroutine is lost

Posted by hansi on Stack Overflow See other posts from Stack Overflow or by hansi
Published on 2012-09-05T20:09:05Z Indexed on 2012/09/05 21:38 UTC
Read the original article Hit count: 174

Filed under:
|
|
|

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:

© Stack Overflow or respective owner

Related posts about perl

Related posts about hash