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:
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.
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