http://qs1969.pair.com?node_id=449740

in reply to Re^2: re-useing a hash

Then me thinks you have some other bug making you think the hash isn't empty. Actually blindly following the advice given so far has caused some additional problems, namely scoping issues.

Lets examine a quick example:

```#!/usr/bin/perl
use strict;
use warnings;

use vars qw(%hash);

sub foo {
\$hash{\$_[0]}+=3;
}

sub bar {
\$hash{\$_[0]}++;
foo(\$_[0]);
}

foreach my \$i (0..10) {
my %hash;

\$hash{\$i} = \$i*3;
bar(\$i);
foo(\$i);

foreach my \$j (sort keys %hash) {
print "hash{\$j} = \$hash{\$j}\n";
}
}
print "done\n";

foreach my \$j (sort keys %hash) {
print "hash{\$j} = \$hash{\$j}\n";
}
Ok, it looks a bit convoluted, definitely contrived, but hey it's just an example. Running through the program through our brains, we're creating a hash with a key of 0 to 10, and setting its value to 3*x, then calling bar() using that index. Bar increments that hash element x by one, then calls foo() which adds 3 more so the value of %hash{0} at this point should be 4. Then we call foo() again, so we're up to 7. %hash{1} should similarly get a value of 3+1+3+3=10 etc.

Oh, and each time through we should end up with a new empty hash too, so if we see repeaters, then the hash is sticking around

Run the code and we get this output:

```hash{0} = 0
hash{1} = 3
hash{2} = 6
hash{3} = 9
hash{4} = 12
hash{5} = 15
hash{6} = 18
hash{7} = 21
hash{8} = 24
hash{9} = 27
hash{10} = 30
done
hash{0} = 7
hash{1} = 7
hash{10} = 7
hash{2} = 7
hash{3} = 7
hash{4} = 7
hash{5} = 7
hash{6} = 7
hash{7} = 7
hash{8} = 7
hash{9} = 7